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

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

// POST - create allergy
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, severity, notes } = body;

    if (!childId || !name) {
      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 [allergy] = await sql.unsafe(
      `INSERT INTO allergies (child_id, name, severity, notes)
       VALUES ($1, $2, $3, $4)
       RETURNING id, name, severity, notes`,
      [childId, name, severity || "mild", notes || null]
    );

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

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

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

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