import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/admin-auth";
import { sql } from "@/db";

export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const { id: childId } = await params;
    const rows = await sql`
      SELECT
        COUNT(DISTINCT fd.id) as feed_count,
        COUNT(DISTINCT dl.id) as diaper_count,
        COUNT(DISTINCT sl.id) as sleep_count,
        COUNT(DISTINCT v.id) as vaccination_count,
        COUNT(DISTINCT g.id) as growth_count
      FROM children c
      LEFT JOIN feeds fd ON fd.child_id = c.id
      LEFT JOIN diapers_logs dl ON dl.child_id = c.id
      LEFT JOIN sleeps sl ON sl.child_id = c.id
      LEFT JOIN vaccinations v ON v.child_id = c.id
      LEFT JOIN growth g ON g.child_id = c.id
      WHERE c.id = ${childId}
    `;
    return NextResponse.json(rows[0] || {});
  } catch (error) {
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

export async function DELETE(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const { id: childId } = await params;
    if (!childId) return NextResponse.json({ error: "childId required" }, { status: 400 });

    // Delete chat messages first (FK on session_id)
    const sessionRows = await sql`SELECT id FROM chat_sessions WHERE child_id = ${childId}`;
    const sessionIds = sessionRows.map((r: any) => r.id);
    if (sessionIds.length > 0) {
      await sql`DELETE FROM chat_messages WHERE session_id = ANY(${sessionIds})`;
    }
    await sql`DELETE FROM chat_sessions WHERE child_id = ${childId}`;
    await sql`DELETE FROM milestone_achievements WHERE child_id = ${childId}`;
    await sql`DELETE FROM illness_logs WHERE child_id = ${childId}`;
    await sql`DELETE FROM doctor_visits WHERE child_id = ${childId}`;
    await sql`DELETE FROM allergies WHERE child_id = ${childId}`;
    await sql`DELETE FROM medicines WHERE child_id = ${childId}`;
    await sql`DELETE FROM medications WHERE child_id = ${childId}`;
    await sql`DELETE FROM growth WHERE child_id = ${childId}`;
    await sql`DELETE FROM vaccinations WHERE child_id = ${childId}`;
    await sql`DELETE FROM sleeps WHERE child_id = ${childId}`;
    await sql`DELETE FROM diapers_logs WHERE child_id = ${childId}`;
    await sql`DELETE FROM feeds WHERE child_id = ${childId}`;
    await sql`DELETE FROM children WHERE id = ${childId}`;

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Admin child delete error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}
