import { NextRequest, NextResponse } from "next/server";
import { createAdminClient } from "@/lib/supabase/server";
import { sanitizeDeep } from "@/lib/sanitize";
import { computeCompleteness } from "@/lib/types";

export async function GET(_req: NextRequest, { params }: { params: { id: string } }) {
  const supabase = createAdminClient();
  const { data, error } = await supabase.from("games").select("*").eq("id", params.id).single();
  if (error || !data) return NextResponse.json({ error: "Not found" }, { status: 404 });
  return NextResponse.json(data);
}

export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
  const supabase = createAdminClient();
  const body = sanitizeDeep(await req.json());

  // If the caller is trying to move status to 'published', enforce the
  // minimum content bar server-side — the admin UI disables the button,
  // but this is the actual gate.
  if (body.status === "published") {
    const { data: current } = await supabase.from("games").select("*").eq("id", params.id).single();
    const merged = { ...current, ...body };
    const wordCount = (merged.overview ?? "").trim().split(/\s+/).filter(Boolean).length;
    const { missing } = computeCompleteness(merged);

    const blockers = [...missing];
    if (wordCount < 600) blockers.push(`600+ words of content (currently ~${wordCount})`);

    if (blockers.length > 0) {
      return NextResponse.json(
        { error: "Cannot publish — minimum content bar not met", missing: blockers },
        { status: 422 }
      );
    }
  }

  const { data, error } = await supabase
    .from("games")
    .update(body)
    .eq("id", params.id)
    .select()
    .single();

  if (error) return NextResponse.json({ error: error.message }, { status: 400 });
  return NextResponse.json(data);
}
