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

// GET /api/garments/packing?childId=&season=&occasion=&days=3
// Returns active garments matching size + season + occasion, grouped by category.
// Pure SQL — no AI.
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");
  const season = searchParams.get("season");
  const occasion = searchParams.get("occasion");

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

  let rows;
  if (season && occasion) {
    rows = await sql`
      SELECT * FROM garments
      WHERE family_id = ${familyId} AND child_id = ${childId} AND status = 'active'
        AND ${season} = ANY(seasons) AND ${occasion} = ANY(occasion_tags)
      ORDER BY category, name`;
  } else if (season) {
    rows = await sql`
      SELECT * FROM garments
      WHERE family_id = ${familyId} AND child_id = ${childId} AND status = 'active'
        AND ${season} = ANY(seasons)
      ORDER BY category, name`;
  } else if (occasion) {
    rows = await sql`
      SELECT * FROM garments
      WHERE family_id = ${familyId} AND child_id = ${childId} AND status = 'active'
        AND ${occasion} = ANY(occasion_tags)
      ORDER BY category, name`;
  } else {
    rows = await sql`
      SELECT * FROM garments
      WHERE family_id = ${familyId} AND child_id = ${childId} AND status = 'active'
      ORDER BY category, name`;
  }

  const baseUrl = process.env.R2_PUBLIC_URL || `https://pub-${process.env.R2_ACCOUNT_ID}.r2.dev`;

  // Group by category
  const grouped: Record<string, { id: string; name: string; sizeLabel: string; thumbUrl: string; checked: boolean }[]> = {};
  for (const g of rows) {
    const cat = g.category as string;
    if (!grouped[cat]) grouped[cat] = [];
    grouped[cat].push({
      id: g.id as string,
      name: (g.name as string) || cat,
      sizeLabel: g.size_label as string,
      thumbUrl: `${baseUrl}/${g.thumb_key}`,
      checked: false,
    });
  }

  return NextResponse.json({ success: true, groups: grouped, total: rows.length });
}
