import { NextRequest, NextResponse } from "next/server";
import { revalidatePath, revalidateTag } from "next/cache";
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)
    .single();
  if (!profile?.is_active) return { ok: false as const, status: 403, error: "Inactive" };
  if (!["administrator", "admin", "editor"].includes(profile.role)) {
    return { ok: false as const, status: 403, error: "Insufficient permissions" };
  }
  return { ok: true as const, userId: user.id };
}

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

  const { id } = await params;
  const { action, note } = (await req.json()) as { action: string; note?: string };

  const admin = createAdminClient();
  const nowIso = new Date().toISOString();

  let nextStatus = "";
  let extras: Record<string, any> = {};

  if (action === "approve") {
    nextStatus = "published";
    extras.published_at = nowIso;
  } else if (action === "reject") {
    nextStatus = "rejected";
  } else if (action === "needs_human") {
    nextStatus = "needs_human_rewrite";
  } else {
    return NextResponse.json({ error: "Unknown action" }, { status: 400 });
  }

  const { data, error } = await admin
    .from("ai_rewritten_articles")
    .update({
      status: nextStatus,
      reviewer_id: auth.userId,
      reviewer_note: note || null,
      reviewed_at: nowIso,
      updated_at: nowIso,
      ...extras,
    })
    .eq("id", id)
    .select("id, slug, original_submission_id")
    .single();

  if (error || !data) return NextResponse.json({ error: error?.message || "Not found" }, { status: 500 });

  if (action === "approve") {
    await admin
      .from("ai_original_submissions")
      .update({ published_rewrite_id: (data as any).id })
      .eq("id", (data as any).original_submission_id);
  }

  const slug = (data as any).slug as string;
  for (const path of [
    "/news",
    `/news/${slug}`,
    `/articles/${slug}`,
    "/home-page",
    "/technology",
    "/gear",
    "/show-coverage",
    "/sitemap.xml",
  ]) {
    try { revalidatePath(path); } catch {}
  }
  try { revalidateTag("articles"); } catch {}

  return NextResponse.json({ ok: true, id: (data as any).id, status: nextStatus, slug });
}
