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

function toDto(g: Record<string, unknown>) {
  const appUrl = process.env.NEXT_PUBLIC_APP_URL || "";
  const ik = g.image_key as string | null;
  const tk = g.thumb_key as string | null;
  return {
    id: g.id,
    familyId: g.family_id,
    childId: g.child_id,
    name: g.name,
    category: g.category,
    sizeLabel: g.size_label,
    colors: g.colors || [],
    seasons: g.seasons || [],
    occasionTags: g.occasion_tags || [],
    imageKey: ik,
    thumbKey: tk,
    // Proxy through /api/img — never expose raw pub-*.r2.dev URLs (blocked by Cloudflare Bot Mgmt)
    imageUrl: ik ? `${appUrl}/api/img?key=${encodeURIComponent(ik)}` : null,
    thumbUrl: tk ? `${appUrl}/api/img?key=${encodeURIComponent(tk)}` : null,
    status: g.status,
    acquiredVia: g.acquired_via,
    giftFrom: g.gift_from,
    visionMetadata: g.vision_metadata,
    createdAt: g.created_at,
    updatedAt: g.updated_at,
  };
}

// GET /api/garments/[id]
export async function GET(_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;

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

  const wears = await sql`
    SELECT id, worn_on, memory_id, created_at FROM garment_wears
    WHERE garment_id = ${id} AND family_id = ${familyId}
    ORDER BY worn_on DESC`;

  return NextResponse.json({ success: true, item: toDto(rows[0]), wears });
}

// PATCH /api/garments/[id]
export async function PATCH(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;

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

  let body: Record<string, unknown>;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  const VALID_STATUSES = ["active", "stored", "outgrown", "donated"];
  if (body.status && !VALID_STATUSES.includes(body.status as string)) {
    return NextResponse.json({ error: "Invalid status" }, { status: 400 });
  }
  if (body.category && !GARMENT_CATEGORIES.includes(body.category as never)) {
    return NextResponse.json({ error: "Invalid category" }, { status: 400 });
  }

  const rows = await sql`
    UPDATE garments SET
      name            = COALESCE(${body.name as string | null ?? null}, name),
      category        = COALESCE(${body.category as string | null ?? null}, category),
      size_label      = COALESCE(${body.sizeLabel as string | null ?? null}, size_label),
      colors          = COALESCE(${body.colors as string[] | null ?? null}, colors),
      seasons         = COALESCE(${body.seasons as string[] | null ?? null}, seasons),
      occasion_tags   = COALESCE(${body.occasionTags as string[] | null ?? null}, occasion_tags),
      status          = COALESCE(${body.status as string | null ?? null}, status),
      acquired_via    = COALESCE(${body.acquiredVia as string | null ?? null}, acquired_via),
      gift_from       = COALESCE(${body.giftFrom as string | null ?? null}, gift_from),
      vision_metadata = COALESCE(${body.visionMetadata ? JSON.stringify(body.visionMetadata) : null}, vision_metadata),
      updated_at      = now()
    WHERE id = ${id} AND family_id = ${familyId}
    RETURNING *`;

  return NextResponse.json({ success: true, item: toDto(rows[0]) });
}

// DELETE /api/garments/[id]
export async function DELETE(_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;

  const rows = await sql`DELETE FROM garments WHERE id = ${id} AND family_id = ${familyId} RETURNING id`;
  if (!rows[0]) return NextResponse.json({ error: "Not found" }, { status: 404 });

  return NextResponse.json({ success: true });
}
