

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

function isUuid(v: string) {
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v);
}

export async function POST(req: Request) {
  try {
    // Session courante
    const sb = createRouteHandlerClient({ cookies });
    const { data: { user } } = await sb.auth.getUser();
    if (!user) return new NextResponse("Unauthorized", { status: 401 });

    // Vérifie Staff
    const { data: me } = await sb
      .from("staff_users")
      .select("is_staff, super_staff")
      .eq("user_id", user.id)
      .maybeSingle();
    if (!me?.is_staff) return new NextResponse("Forbidden", { status: 403 });

    // Récupère les paramètres
    const form = await req.formData();
    const org_id = String(form.get("org_id") || "");
    const target_user_id = String(form.get("user_id") || "");

    if (!org_id || !target_user_id) {
      return NextResponse.json({ error: "invalid_input" }, { status: 400 });
    }
    if (!isUuid(org_id) || !isUuid(target_user_id)) {
      return NextResponse.json({ error: "invalid_uuid" }, { status: 400 });
    }

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

    // S'assure que le membership existe
    const { data: member, error: memberErr } = await admin
      .from("organization_members")
      .select("user_id, org_id, revoked")
      .eq("org_id", org_id)
      .eq("user_id", target_user_id)
      .maybeSingle();

    if (memberErr) {
      return NextResponse.json({ error: memberErr.message }, { status: 400 });
    }
    if (!member) {
      return NextResponse.json({ error: "membership_not_found" }, { status: 404 });
    }

    // Annule la révocation
    const { error } = await admin
      .from("organization_members")
      .update({ revoked: false, revoked_at: null })
      .eq("org_id", org_id)
      .eq("user_id", target_user_id);

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

    // (Filet de sécurité) Retire un éventuel ban historique
    try {
      await (admin.auth.admin as any).updateUserById(target_user_id, {
        banned_until: null,
        user_metadata: { app_banned: false },
      });
    } catch (_) {
      // on ignore si l'API admin n'est pas accessible ; l'essentiel est la levée de révocation au niveau org
    }

    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, revoked: false });
  } catch (e: any) {
    return new NextResponse(e?.message || "Internal Server Error", { status: 500 });
  }
}