import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily, requireOwnership } from "@/lib/auth";

// GET - list doctor visits for a child
export async function GET(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  const { searchParams } = new URL(request.url);
  const childId = searchParams.get("childId");

  if (!childId) {
    return NextResponse.json({ error: "childId required" }, { status: 400 });
  }

  const ownership = await requireOwnership(childId, "children", "Child");
  if (!ownership.success) {
    return NextResponse.json({ error: ownership.error }, { status: ownership.status });
  }

  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) {
  const auth = await requireFamily();
  if (!auth.success) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  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 ownership = await requireOwnership(childId, "children", "Child");
    if (!ownership.success) {
      return NextResponse.json({ error: ownership.error }, { status: ownership.status });
    }

    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 });
  }
}

// DELETE - delete visit
export async function DELETE(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  const { searchParams } = new URL(request.url);
  const id = searchParams.get("id");

  if (!id) {
    return NextResponse.json({ error: "ID required" }, { status: 400 });
  }

  try {
    const visit = await sql.unsafe(
      `SELECT v.id, v.child_id FROM doctor_visits v
       JOIN children c ON c.id = v.child_id
       WHERE v.id = $1`,
      [id]
    );

    if (!visit || visit.length === 0) {
      return NextResponse.json({ error: "Visit not found or access denied" }, { status: 404 });
    }

    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 });
  }
}