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

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 {
    const sb = createRouteHandlerClient({ cookies });
    const { data: { user } } = await sb.auth.getUser();
    if (!user) return new NextResponse("Unauthorized", { status: 401 });

    // Staff-only guard
    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 });

    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 });
    }
    if (target_user_id === user.id) {
      return NextResponse.json({ error: "self_revoke_forbidden" }, { status: 400 });
    }

    // Admin client (server-only key)
    const admin = createClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.SUPABASE_SERVICE_ROLE_KEY!,
      { auth: { autoRefreshToken: false, persistSession: false } }
    );

    // Optional: ensure membership exists (no-op if already revoked)
    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 });
    }

    // Revoke membership (logical delete)
    const { error } = await admin
      .from("organization_members")
      .update({ revoked: true, revoked_at: new Date().toISOString() })
      .eq("org_id", org_id)
      .eq("user_id", target_user_id);

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

    // Envoyer un email de révocation à l'utilisateur
    try {
      const { data: userData } = await admin.auth.admin.getUserById(target_user_id);
      const to = userData?.user?.email;
      const firstName = userData?.user?.user_metadata?.first_name || undefined;
      const { data: orgRow } = await admin.from('organizations').select('name').eq('id', org_id).maybeSingle();
      const revokedBy = user.email || 'Administrateur';
      if (to) {
        await sendAccessRevokedEmail(to, {
          firstName: firstName || '',
          organizationName: String(orgRow?.name || ''),
          userEmail: to,
          revocationDate: new Date().toLocaleString('fr-FR'),
          revokedBy,
        });
      }
    } catch (e) {
      console.warn('⚠️ Envoi email révocation (staff) échoué, non-bloquant:', (e as any)?.message || e);
    }

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