import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { createAdminClient } from "@/lib/supabase/admin";

export const runtime = "nodejs";

async function requireAdmin() {
  const sb = await createClient();
  const { data: { user } } = await sb.auth.getUser();
  if (!user) return { ok: false as const, status: 401, error: "Unauthorized" };
  const { data: profile } = await sb
    .from("user_profiles")
    .select("role, is_active")
    .eq("id", user.id)
    .maybeSingle();
  if (!profile?.is_active) return { ok: false as const, status: 403, error: "Inactive" };
  if (!["administrator", "admin"].includes((profile as any).role)) {
    return { ok: false as const, status: 403, error: "Insufficient permissions" };
  }
  return { ok: true as const };
}

const ALLOWED_FIELDS = new Set([
  "name",
  "click_url",
  "image_path",
  "size",
  "start_date",
  "end_date",
  "status",
  "notes",
]);

export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const guard = await requireAdmin();
  if (!guard.ok) return NextResponse.json({ error: guard.error }, { status: guard.status });

  const { id } = await params;
  const body = (await req.json()) as Record<string, any>;
  const patch: Record<string, any> = {};
  for (const [k, v] of Object.entries(body)) {
    if (ALLOWED_FIELDS.has(k)) patch[k] = v;
  }
  if (Object.keys(patch).length === 0) {
    return NextResponse.json({ error: "No allowed fields supplied" }, { status: 400 });
  }
  patch.updated_at = new Date().toISOString();

  const admin = createAdminClient();
  const { data, error } = await admin
    .from("banner_creatives")
    .update(patch)
    .eq("id", id)
    .select("id, slug, status")
    .single();
  if (error || !data) return NextResponse.json({ error: error?.message || "Not found" }, { status: 500 });

  return NextResponse.json({ ok: true, banner: data });
}
