import { createClient } from "@supabase/supabase-js";

/**
 * Server-only Supabase client authenticated as `service_role`. Used for the
 * admin auth API (createUser, deleteUser, listUsers). Bypasses RLS — never
 * import this from client components.
 *
 * Needs SUPABASE_SERVICE_ROLE_KEY in the env (set as a Coolify app env var,
 * NOT prefixed with NEXT_PUBLIC_ so it never ships to the client bundle).
 */
export function createAdminClient(schema?: string) {
  const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
  const key = process.env.SUPABASE_SERVICE_ROLE_KEY;
  if (!url || !key) {
    throw new Error(
      "createAdminClient: missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY",
    );
  }
  return createClient(url, key, {
    auth: { persistSession: false, autoRefreshToken: false },
    db: { schema: schema || process.env.NEXT_PUBLIC_SUPABASE_SCHEMA || "av" },
  });
}
