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

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: familyId } = await params;
    if (!familyId) return NextResponse.json({ error: "familyId required" }, { status: 400 });

    // Get child IDs before deleting
    const childRows = await sql`SELECT id FROM children WHERE family_id = ${familyId}`;
    const childIds = childRows.map((r: any) => r.id);

    if (childIds.length > 0) {
      // Delete child data in FK order
      const chatSessionRows = await sql`SELECT id FROM chat_sessions WHERE child_id = ANY(${childIds})`;
      const sessionIds = chatSessionRows.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 = ANY(${childIds})`;
      await sql`DELETE FROM milestone_achievements WHERE child_id = ANY(${childIds})`;
      await sql`DELETE FROM illness_logs WHERE child_id = ANY(${childIds})`;
      await sql`DELETE FROM doctor_visits WHERE child_id = ANY(${childIds})`;
      await sql`DELETE FROM allergies WHERE child_id = ANY(${childIds})`;
      await sql`DELETE FROM medicines WHERE child_id = ANY(${childIds})`;
      await sql`DELETE FROM medications WHERE child_id = ANY(${childIds})`;
      await sql`DELETE FROM growth WHERE child_id = ANY(${childIds})`;
      await sql`DELETE FROM vaccinations WHERE child_id = ANY(${childIds})`;
      await sql`DELETE FROM sleeps WHERE child_id = ANY(${childIds})`;
      await sql`DELETE FROM diapers_logs WHERE child_id = ANY(${childIds})`;
      await sql`DELETE FROM feeds WHERE child_id = ANY(${childIds})`;
      await sql`DELETE FROM children WHERE family_id = ${familyId}`;
    }

    // Delete family-level data
    await sql`DELETE FROM family_invites WHERE family_id = ${familyId}`;
    await sql`DELETE FROM medication_doses WHERE family_id = ${familyId}`;
    const profileRows = await sql`SELECT id FROM member_profiles WHERE family_id = ${familyId}`;
    const profileIds = profileRows.map((r: any) => r.id);
    if (profileIds.length > 0) {
      await sql`DELETE FROM recommended_products WHERE profile_id = ANY(${profileIds})`;
    }
    await sql`DELETE FROM member_profiles WHERE family_id = ${familyId}`;
    await sql`DELETE FROM memories WHERE family_id = ${familyId}`;
    await sql`DELETE FROM attachments WHERE family_id = ${familyId}`;
    await sql`UPDATE support_tickets SET family_id = NULL WHERE family_id = ${familyId}`;
    await sql`UPDATE audit_log SET family_id = NULL WHERE family_id = ${familyId}`;
    await sql`DELETE FROM family_members WHERE family_id = ${familyId}`;
    await sql`DELETE FROM families WHERE id = ${familyId}`;

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