import { NextResponse } from "next/server";
import { sql } from "@/db";
import { validateSession, requireFamily } from "@/lib/auth";
import { checkChildLimit } from "@/lib/quota";
import { toProxyUrl } from "@/lib/r2-proxy";

// GET - list children (family only)
export async function GET(request: Request) {
  const auth = await requireFamily();
  if (!auth.success) {
    return NextResponse.json({ error: auth.error }, { status: auth.status });
  }

  const familyId = auth.session!.familyId!;

  try {
    const rows = await sql.unsafe(
      `SELECT id, name, birth_date as "birthDate", sex, stage, image_url as "imageUrl", created_at as "createdAt" FROM children WHERE family_id = $1 ORDER BY created_at DESC`,
      [familyId]
    );
    const children = (rows || []).map((c: any) => ({
      ...c,
      imageUrl: toProxyUrl(c.imageUrl) ?? null,
    }));
    return NextResponse.json({ children });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}

// POST - create child (family only)
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 { name, birthDate, sex } = body;
    const familyId = auth.session!.familyId!;

    if (!familyId || !name || !birthDate || !sex) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
    }

    const limitCheck = await checkChildLimit(familyId);
    if (!limitCheck.allowed) {
      return NextResponse.json(
        { error: limitCheck.message, reason: limitCheck.reason, currentCount: limitCheck.currentCount, limit: limitCheck.limit },
        { status: 403 }
      );
    }

    const [child] = await sql.unsafe(
      `INSERT INTO children (family_id, name, birth_date, sex, stage) VALUES ($1, $2, $3, $4, 'newborn') RETURNING id, name, birth_date as "birthDate", sex, stage`,
      [familyId, name, birthDate, sex]
    );

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