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

// GET - list illness logs 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 illnesses = await sql.unsafe(
      `SELECT id, name, start_date as "startDate", end_date as "endDate", notes, created_at as "createdAt"
       FROM illness_logs WHERE child_id = $1 ORDER BY start_date DESC`,
      [childId]
    );
    return NextResponse.json({ illnesses: illnesses || [] });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// POST - create illness log
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, name, startDate, endDate, notes } = body;

    if (!childId || !name || !startDate) {
      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 [illness] = await sql.unsafe(
      `INSERT INTO illness_logs (child_id, name, start_date, end_date, notes)
       VALUES ($1, $2, $3, $4, $5)
       RETURNING id, name, start_date as "startDate", end_date as "endDate", notes`,
      [childId, name, startDate, endDate || null, notes || null]
    );

    return NextResponse.json({ success: true, illness });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// DELETE - delete illness log
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 illness = await sql.unsafe(
      `SELECT i.id, i.child_id FROM illness_logs i
       JOIN children c ON c.id = i.child_id
       WHERE i.id = $1`,
      [id]
    );

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

    await sql.unsafe(`DELETE FROM illness_logs WHERE id = $1`, [id]);
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}