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({ error: "No customer linked" }, { status: 404 })
  }

  const customer = await query(
    `SELECT c.id, c.customer_type, c.source, c.notes as customer_notes,
            cs.name as status_name, cs.color as status_color,
            cc.company_name, cc.registration_number, cc.tax_id,
            cc.website, cc.industry, cc.company_size, cc.annual_revenue,
            ic.first_name, ic.last_name, ic.job_title
     FROM customers c
     LEFT JOIN customer_statuses cs ON cs.id = c.status_id
     LEFT JOIN company_customers cc ON cc.customer_id = c.id
     LEFT JOIN individual_customers ic ON ic.customer_id = c.id
     WHERE c.id = $1 AND c.deleted_at IS NULL`,
    [session.customerId],
  )

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

  const contacts = await query(
    `SELECT type, value, label, is_primary
     FROM contact_information
     WHERE customer_id = $1 AND deleted_at IS NULL
     ORDER BY is_primary DESC, type ASC`,
    [session.customerId],
  )

  return NextResponse.json({
    profile: customer.rows[0],
    contacts: contacts.rows,
  })
}
