import { NextResponse } from "next/server"; import { sql } from "@/db"; // GET - list doctor visits for a child export async function GET(request: Request) { const { searchParams } = new URL(request.url); const childId = searchParams.get("childId") || "default"; try { const visits = await sql.unsafe( `SELECT id, doctor_name as "doctorName", reason, visit_date as "date", notes, created_at as "createdAt" FROM doctor_visits WHERE child_id = $1 ORDER BY visit_date DESC`, [childId] ); return NextResponse.json({ visits: visits || [] }); } catch (error) { console.error(error); return NextResponse.json({ error: String(error) }, { status: 500 }); } } // POST - create visit export async function POST(request: Request) { try { const body = await request.json(); const { childId, doctorName, reason, date, notes } = body; if (!childId || !doctorName || !date) { return NextResponse.json({ error: "Missing required fields" }, { status: 400 }); } const [visit] = await sql.unsafe( `INSERT INTO doctor_visits (child_id, doctor_name, reason, visit_date, notes) VALUES ($1, $2, $3, $4, $5) RETURNING id, doctor_name as "doctorName", reason, visit_date as "date", notes`, [childId, doctorName, reason || null, date, notes || null] ); return NextResponse.json({ success: true, visit }); } catch (error) { console.error(error); return NextResponse.json({ error: String(error) }, { status: 500 }); } } // PATCH - update visit export async function PATCH(request: Request) { try { const body = await request.json(); const { id, doctorName, reason, date, notes } = body; if (!id || !doctorName || !date) { return NextResponse.json({ error: "Missing required fields" }, { status: 400 }); } const [visit] = await sql.unsafe( `UPDATE doctor_visits SET doctor_name = $1, reason = $2, visit_date = $3, notes = $4, updated_at = NOW() WHERE id = $5 RETURNING id, doctor_name as "doctorName", reason, visit_date as "date", notes`, [doctorName, reason, date, notes, id] ); return NextResponse.json({ success: true, visit }); } catch (error) { console.error(error); return NextResponse.json({ error: String(error) }, { status: 500 }); } } // DELETE - delete visit export async function DELETE(request: Request) { const { searchParams } = new URL(request.url); const id = searchParams.get("id"); if (!id) { return NextResponse.json({ error: "ID required" }, { status: 400 }); } try { await sql.unsafe(`DELETE FROM doctor_visits WHERE id = $1`, [id]); return NextResponse.json({ success: true }); } catch (error) { console.error(error); return NextResponse.json({ error: String(error) }, { status: 500 }); } }