// app/api/access/[memberId]/unrevoke/route.ts
import { NextResponse } from "next/server";
import { cookies, headers } from "next/headers";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { createClient } from "@supabase/supabase-js";

type MemberRecord = { role: string; revoked: boolean };

function orgId() {
  return headers().get("x-active-org-id") || cookies().get("active_org_id")?.value || null;
}
export async function POST(_req: Request, { params }: { params: { memberId: string } }) {
  // Resolve org_id from headers/cookies first
  let org_id = orgId();

  const sb = createRouteHandlerClient({ cookies });
  const { data: { user } } = await sb.auth.getUser();
  if (!user) return new NextResponse("Unauthorized", { status: 401 });

  let isStaff = false;
  try {
    const { data: staffRow } = await sb.from('staff_users').select('is_staff').eq('user_id', user.id).maybeSingle();
    isStaff = !!staffRow?.is_staff;
  } catch {}

  // If no org_id yet, and caller is staff, try to resolve organization from the target member
  if (!org_id && isStaff) {
    try {
      const { data: target } = await sb.from('org_members').select('org_id').eq('id', params.memberId).maybeSingle();
      if (target?.org_id) org_id = target.org_id;
    } catch {}
  }

  // Non-staff callers require an active org
  if (!org_id && !isStaff) return new NextResponse("no_active_org", { status: 400 });

  // If org is known, verify caller has admin role in that org. Staff bypass this org check (global staff).
  if (org_id) {
    const { data: meRow } = await sb
      .from("org_members")
      .select("role,revoked")
      .eq("org_id", org_id)
      .eq("user_id", user.id)
      .maybeSingle();
    const me = (meRow as MemberRecord | null) ?? null;
    if (!me || me.revoked || !["ADMIN", "SUPER_ADMIN"].includes(me.role)) {
      return new NextResponse("Forbidden", { status: 403 });
    }
  }

  const admin = createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!,
    { auth: { autoRefreshToken: false, persistSession: false } }
  );
  const { error } = await admin.from("org_members")
    .update({ revoked: false, revoked_at: null })
    .eq("org_id", org_id).eq("id", params.memberId);
  if (error) return NextResponse.json({ error: error.message }, { status: 400 });

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