import { createClient, type SupabaseClient } from '@supabase/supabase-js';
import { appEnv, ensureRuntimeConfigLoaded } from '@/env';

let client: SupabaseClient | null = null;
let clientKey = '';

export function getSupabaseClient() {
  if (!appEnv.supabaseUrl || !appEnv.supabasePublishableKey) return null;
  const nextClientKey = `${appEnv.supabaseUrl}|${appEnv.supabasePublishableKey}`;
  if (!client || clientKey !== nextClientKey) {
    client = createClient(appEnv.supabaseUrl, appEnv.supabasePublishableKey, {
      auth: {
        persistSession: true,
        autoRefreshToken: true,
        detectSessionInUrl: true,
      },
    });
    clientKey = nextClientKey;
  }
  return client;
}

export async function ensureSupabaseClient() {
  await ensureRuntimeConfigLoaded();
  return getSupabaseClient();
}

export async function getSupabaseAccessToken() {
  const supabase = await ensureSupabaseClient();
  if (!supabase) return null;
  const { data } = await supabase.auth.getSession();
  return data.session?.access_token || null;
}
