import { NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"

export interface PortalSession {
  userId: string
  role: string
  customerId: string | null
}

export async function getPortalSession(): Promise<PortalSession | NextResponse> {
  const user = await getSessionUser()
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 }) as NextResponse
  }
  if (user.role !== "client") {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 }) as NextResponse
  }

  const link = await query(
    "SELECT customer_id FROM client_customer_links WHERE user_id = $1",
    [user.id],
  )

  return {
    userId: user.id,
    role: user.role,
    customerId: link.rows[0]?.customer_id || null,
  }
}

export function isPortalError(session: PortalSession | NextResponse): session is NextResponse {
  return session instanceof NextResponse
}
