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

// Apply default limits to all free-tier families
export async function POST(request: Request) {
  const auth = await requireAdmin(request);
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  try {
    const body = await request.json();
    const { maxChildren, maxMembers } = body;

    if (!maxChildren || !maxMembers) {
      return NextResponse.json({ error: "maxChildren and maxMembers required" }, { status: 400 });
    }

    const result = await sql`
      UPDATE families
      SET max_children = ${maxChildren}, max_members = ${maxMembers}, updated_at = NOW()
      WHERE tier = 'free'
      RETURNING id
    `;

    return NextResponse.json({ success: true, updated: result.length });
  } catch (error) {
    console.error("Limits update error:", error);
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}
