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

export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getPortalSession()
  if (isPortalError(session)) return session
  const { id } = await params

  if (!session.customerId) {
    return NextResponse.json({ error: "No customer linked" }, { status: 404 })
  }

  const invoice = await query(
    `SELECT i.id, i.invoice_number, i.subtotal, i.tax_percent, i.tax_amount,
            i.discount_percent, i.discount_amount, i.total_amount, i.currency,
            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.id = $1 AND i.customer_id = $2`,
    [id, session.customerId],
  )

  if (!invoice.rows[0]) {
    return NextResponse.json({ error: "Invoice not found" }, { status: 404 })
  }

  const items = await query(
    `SELECT ii.description, ii.quantity, ii.unit_price, ii.discount_percent, ii.total_price
     FROM invoice_items ii
     WHERE ii.invoice_id = $1`,
    [id],
  )

  const receipts = await query(
    `SELECT id, receipt_number, file_url, issued_at
     FROM receipts
     WHERE invoice_id = $1
     ORDER BY issued_at DESC`,
    [id],
  )

  return NextResponse.json({
    invoice: invoice.rows[0],
    items: items.rows,
    receipts: receipts.rows,
  })
}
