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

// POST /api/garments/[id]/wear
// Logs that a garment was worn today (or a specific date)
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const auth = await requireFamily();
  if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });

  const familyId = auth.session!.familyId!;
  const { id } = await params;

  // Confirm garment belongs to family
  const garment = await sql`SELECT id FROM garments WHERE id = ${id} AND family_id = ${familyId} LIMIT 1`;
  if (!garment[0]) return NextResponse.json({ error: "Not found" }, { status: 404 });

  let wornOn: string = new Date().toISOString().slice(0, 10); // default today
  let memoryId: string | null = null;

  try {
    const body = await req.json();
    if (body.wornOn) wornOn = body.wornOn;
    if (body.memoryId) memoryId = body.memoryId;
  } catch {
    // body is optional
  }

  const rows = await sql`
    INSERT INTO garment_wears (family_id, garment_id, worn_on, memory_id)
    VALUES (${familyId}, ${id}, ${wornOn}, ${memoryId})
    RETURNING *`;

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