import { NextRequest, NextResponse } from "next/server";
import { requireFamily } from "@/lib/auth";
import { sql } from "@/db";
import { getGurgaonWeather } from "@/lib/wardrobe/weather";
import { buildOutfits, type GarmentRow } from "@/lib/wardrobe/outfit";

// GET /api/garments/outfit?childId=&occasion=
// Returns deterministic outfit suggestions based on today's weather.
// No LLM — pure filter + rule logic.
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 occasion = searchParams.get("occasion");

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

  const weather = await getGurgaonWeather();

  let rows;
  if (occasion) {
    rows = await sql`
      SELECT * FROM garments
      WHERE family_id = ${familyId} AND child_id = ${childId} AND status = 'active'
        AND ${weather.season} = ANY(seasons)
        AND ${occasion} = ANY(occasion_tags)
        AND category IN ('top','bottom','dress','onesie')
      ORDER BY RANDOM()`;
  } else {
    rows = await sql`
      SELECT * FROM garments
      WHERE family_id = ${familyId} AND child_id = ${childId} AND status = 'active'
        AND ${weather.season} = ANY(seasons)
        AND category IN ('top','bottom','dress','onesie')
      ORDER BY RANDOM()`;
  }

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

  const garments: GarmentRow[] = rows.map(g => ({
    id: g.id as string,
    name: g.name as string | null,
    category: g.category as string,
    sizeLabel: g.size_label as string,
    colors: (g.colors as string[]) || [],
    seasons: (g.seasons as string[]) || [],
    occasionTags: (g.occasion_tags as string[]) || [],
    thumbKey: g.thumb_key as string,
    imageKey: g.image_key as string,
  }));

  const outfits = buildOutfits(garments, 3);

  const outfitsWithUrls = outfits.map(o => ({
    ...o,
    items: o.items.map(item => ({
      ...item,
      thumbUrl: `${baseUrl}/${item.thumbKey}`,
      imageUrl: `${baseUrl}/${item.imageKey}`,
    })),
  }));

  return NextResponse.json({
    success: true,
    weather,
    weatherBasis: `${weather.description} — ${Math.round(weather.tempC)}°C today in Gurugram`,
    outfits: outfitsWithUrls,
  });
}
