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

export async function GET(request: NextRequest) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const { searchParams } = new URL(request.url)
    const limit = parseInt(searchParams.get("limit") || "50", 10)

    const result = await query(
      `SELECT c.id, c.customer_type,
              ic.first_name, ic.last_name,
              cc.company_name
       FROM customers c
       LEFT JOIN individual_customers ic ON ic.customer_id = c.id
       LEFT JOIN company_customers cc ON cc.customer_id = c.id
       WHERE c.deleted_at IS NULL
       ORDER BY COALESCE(cc.company_name, ic.last_name || ', ' || ic.first_name)
       LIMIT $1`,
      [limit]
    )

    return NextResponse.json(result.rows)
  } catch (error) {
    console.error("Customers API error:", error)
    return NextResponse.json({ error: "Failed to load customers" }, { status: 500 })
  }
}
