import { NextRequest, NextResponse } from "next/server";
import { requireFamily } from "@/lib/auth";
import { sql } from "@/db";

// GET /api/garments/outfits?childId=
export async function GET(req: NextRequest) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;
  const { searchParams } = new URL(req.url);
  const childId = searchParams.get("childId");

  if (!childId) return NextResponse.json({ error: "childId required" }, { status: 400 });

  const rows = await sql`
    SELECT * FROM outfits
    WHERE family_id = ${familyId} AND child_id = ${childId}
    ORDER BY created_at DESC`;

  return NextResponse.json({ success: true, items: rows });
}

// POST /api/garments/outfits
export async function POST(req: NextRequest) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;

  let body: { childId?: string; name?: string; garmentIds?: string[]; occasionTags?: string[] };
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  const { childId, name, garmentIds = [], occasionTags = [] } = body;
  if (!childId || !name) return NextResponse.json({ error: "childId and name required" }, { status: 400 });

  // Verify child belongs to family
  const childCheck = await sql`SELECT id FROM children WHERE id = ${childId} AND family_id = ${familyId} LIMIT 1`;
  if (!childCheck[0]) return NextResponse.json({ error: "Child not found" }, { status: 404 });

  const rows = await sql`
    INSERT INTO outfits (family_id, child_id, name, garment_ids, occasion_tags)
    VALUES (${familyId}, ${childId}, ${name}, ${garmentIds}, ${occasionTags})
    RETURNING *`;

  return NextResponse.json({ success: true, item: rows[0] }, { status: 201 });
}
