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 * FROM suppliers WHERE name ILIKE $1 OR code ILIKE $1 OR email ILIKE $1 OR contact_person ILIKE $1 ORDER BY name ASC`, [`%${search}%`] ); } else { rows = await sql(`SELECT * FROM suppliers ORDER BY name ASC`); } return NextResponse.json(rows); } catch (error) { console.error("[v0] Suppliers GET error:", error); return NextResponse.json( { error: error instanceof Error ? error.message : "Failed to fetch suppliers" }, { 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, country, currency, notes } = body; if (!name || !code) { return NextResponse.json({ error: "Name and code are required" }, { status: 400 }); } const rows = await sql( `INSERT INTO suppliers (name, code, email, phone, address, contact_person, country, currency, notes) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *`, [name, code, email || null, phone || null, address || null, contact_person || null, country || "", currency || "EUR", notes || null] ); return NextResponse.json(rows[0], { status: 201 }); } catch (error) { console.error("[v0] Suppliers POST error:", error); return NextResponse.json( { error: error instanceof Error ? error.message : "Failed to create supplier" }, { status: 500 } ); } }