import { NextResponse } from "next/server";
import { cookies, headers } from "next/headers";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { createClient } from "@supabase/supabase-js";

const ROLES = ["SUPER_ADMIN","ADMIN","AGENT","COMPTA"] as const;
type Role = typeof ROLES[number];

export async function POST(req: Request) {
  // Vérif Staff avec la session (RLS)
  const sb = createRouteHandlerClient({ cookies });
  const { data: { user } } = await sb.auth.getUser();
  if (!user) return new NextResponse("Unauthorized", { status: 401 });

  const { data: me } = await sb.from("staff_users")
    .select("is_staff")
    .eq("user_id", user.id)
    .maybeSingle();

  if (!me?.is_staff) return new NextResponse("Forbidden", { status: 403 });

  // Récupère les paramètres (form POST standard)
  const form = await req.formData();
  const org_id = String(form.get("org_id") || "");
  const user_id = String(form.get("user_id") || "");
  const role = String(form.get("role") || "").toUpperCase() as Role;

  if (!org_id || !user_id || !ROLES.includes(role)) {
    return NextResponse.json({ error: "invalid_input" }, { status: 400 });
  }

  // Client admin (service role) côté serveur
  const admin = createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!, // SERVER ONLY
    { auth: { autoRefreshToken: false, persistSession: false } }
  );

  // Mise à jour du rôle si non révoqué
  const { error } = await admin
    .from("organization_members")
    .update({ role })
    .eq("org_id", org_id)
    .eq("user_id", user_id)
    .eq("revoked", false);

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

  // Si la requête vient d’un submit HTML, on peut rediriger vers la liste
  const accept = headers().get("accept") || "";
  if (accept.includes("text/html")) {
    return NextResponse.redirect(new URL("/staff/utilisateurs", req.url), { status: 303 });
  }

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