import { NextRequest, NextResponse } from "next/server";
import { requireFamily } from "@/lib/auth";
import { tagGarment } from "@/lib/wardrobe/vision";

// POST /api/garments/tag
// Body: { imageKey: string }
// Returns vision-tagged garment metadata
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: { imageKey?: string };
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  const { imageKey } = body;
  if (!imageKey) return NextResponse.json({ error: "imageKey required" }, { status: 400 });

  // Verify the key belongs to this family (key contains family_id by construction)
  if (!imageKey.startsWith(`garments/${familyId}/`)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const result = await tagGarment(imageKey);
  return NextResponse.json({ success: true, ...result });
}
