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

// GET /api/garments/outgrowth?childId=
// Returns active garments that are likely outgrown:
//  - size_label sorts BELOW the most recently-added active garment's size_label
//  - AND no garment_wears in the last 45 days
//
// Size ordering uses an explicit ordered list to avoid lexicographic errors
// (e.g. '9-12m' < '12-18m' by size but '9' > '1' lexicographically).
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 });

  // Fetch all active garments for this child
  const active = await sql`
    SELECT g.id, g.name, g.category, g.size_label, g.thumb_key, g.created_at,
           MAX(gw.worn_on) AS last_worn
    FROM garments g
    LEFT JOIN garment_wears gw ON gw.garment_id = g.id
    WHERE g.family_id = ${familyId} AND g.child_id = ${childId} AND g.status = 'active'
    GROUP BY g.id
    ORDER BY g.created_at DESC`;

  if (active.length === 0) {
    return NextResponse.json({ success: true, candidates: [], currentSizeLabel: null });
  }

  // Find the most recently-added active garment's size_label
  const currentSizeLabel = active[0].size_label as string;
  const currentSizeIdx = GARMENT_SIZE_ORDER.indexOf(currentSizeLabel as never);

  const cutoff = new Date();
  cutoff.setDate(cutoff.getDate() - 45);

  const candidates = active.filter(g => {
    const sizeIdx = GARMENT_SIZE_ORDER.indexOf(g.size_label as never);
    const isSmaller = sizeIdx >= 0 && currentSizeIdx >= 0 && sizeIdx < currentSizeIdx;
    const lastWorn = g.last_worn ? new Date(g.last_worn as string) : null;
    const notWornRecently = !lastWorn || lastWorn < cutoff;
    return isSmaller && notWornRecently;
  });

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

  return NextResponse.json({
    success: true,
    currentSizeLabel,
    candidates: candidates.map(g => ({
      id: g.id,
      name: g.name,
      category: g.category,
      sizeLabel: g.size_label,
      thumbUrl: `${baseUrl}/${g.thumb_key}`,
      lastWorn: g.last_worn,
    })),
  });
}
