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

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

  try {

    // Get all children with family info
    const children = await sql`
      SELECT
        c.id,
        c.name,
        c.birth_date,
        c.family_id,
        f.name as family_name,
        AGE(c.birth_date) as age
      FROM children c
      LEFT JOIN families f ON f.id = c.family_id
      ORDER BY c.created_at DESC
    `;

    return NextResponse.json({
      children: children.map((c: any) => ({
        id: c.id,
        name: c.name,
        birthDate: c.birth_date ? new Date(c.birth_date).toISOString() : null,
        familyId: c.family_id,
        familyName: c.family_name,
        age: c.age || "N/A",
      })),
    });
  } catch (error) {
    console.error("Admin children error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}