import { NextRequest, NextResponse } from "next/server"; import { getDb } from "@/lib/db"; export async function GET(request: NextRequest) { try { const sql = getDb(); const { searchParams } = new URL(request.url); const search = searchParams.get("search") || ""; let rows; if (search) { rows = await sql( `SELECT c.*, COUNT(po.id) AS order_count, COALESCE(SUM( CASE WHEN po.status != 'cancelled' THEN (SELECT COALESCE(SUM(poi.quantity * poi.unit_price), 0) FROM purchase_order_items poi WHERE poi.purchase_order_id = po.id) ELSE 0 END ), 0) AS total_revenue FROM customers c LEFT JOIN purchase_orders po ON po.customer_id = c.id WHERE c.name ILIKE $1 OR c.code ILIKE $1 OR c.email ILIKE $1 OR c.contact_person ILIKE $1 GROUP BY c.id ORDER BY c.name ASC`, [`%${search}%`] ); } else { rows = await sql( `SELECT c.*, COUNT(po.id) AS order_count, COALESCE(SUM( CASE WHEN po.status != 'cancelled' THEN (SELECT COALESCE(SUM(poi.quantity * poi.unit_price), 0) FROM purchase_order_items poi WHERE poi.purchase_order_id = po.id) ELSE 0 END ), 0) AS total_revenue FROM customers c LEFT JOIN purchase_orders po ON po.customer_id = c.id GROUP BY c.id ORDER BY c.name ASC` ); } return NextResponse.json(rows); } catch (error) { console.error("[v0] Customers GET error:", error); return NextResponse.json( { error: error instanceof Error ? error.message : "Failed to fetch customers" }, { status: 500 } ); } } export async function POST(request: NextRequest) { try { const sql = getDb(); const body = await request.json(); const { name, code, email, phone, address, contact_person, notes } = body; if (!name || !code) { return NextResponse.json({ error: "Name and code are required" }, { status: 400 }); } const rows = await sql( `INSERT INTO customers (name, code, email, phone, address, contact_person, notes) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *`, [name, code, email || null, phone || null, address || null, contact_person || null, notes || null] ); return NextResponse.json(rows[0], { status: 201 }); } catch (error) { console.error("[v0] Customers POST error:", error); return NextResponse.json( { error: error instanceof Error ? error.message : "Failed to create customer" }, { status: 500 } ); } }