// Server-only external Supabase admin client. Uses service role — bypasses RLS.
// NEVER import from client code.
import { createClient } from "@supabase/supabase-js";

function createExtAdmin() {
  const url = process.env.EXTERNAL_SUPABASE_URL;
  const key = process.env.EXTERNAL_SUPABASE_SERVICE_ROLE_KEY;
  if (!url || !key) {
    throw new Error(
      "Missing EXTERNAL_SUPABASE_URL or EXTERNAL_SUPABASE_SERVICE_ROLE_KEY",
    );
  }
  return createClient(url, key, {
    auth: { persistSession: false, autoRefreshToken: false },
  });
}

let _ext: ReturnType<typeof createExtAdmin> | undefined;

export const supabaseExtAdmin = new Proxy({} as ReturnType<typeof createExtAdmin>, {
  get(_, prop, receiver) {
    if (!_ext) _ext = createExtAdmin();
    return Reflect.get(_ext, prop, receiver);
  },
});