import { NextResponse } from "next/server"
import { query } from "@/lib/db"
import { getPortalSession, isPortalError } from "../portal-utils"

export async function GET() {
  const session = await getPortalSession()
  if (isPortalError(session)) return session

  if (!session.customerId) {
    return NextResponse.json({ invoices: [] })
  }

  const result = await query(
    `SELECT i.id, i.invoice_number, i.total_amount, i.currency, i.status_id,
            i.issued_date, i.due_date, i.paid_at, s.name as status_name
     FROM invoices i
     LEFT JOIN invoice_statuses s ON s.id = i.status_id
     WHERE i.customer_id = $1
     ORDER BY i.issued_date DESC NULLS LAST`,
    [session.customerId],
  )

  return NextResponse.json({ invoices: result.rows })
}
