export interface SupabaseRuntimeConfig {
  url: string;
  anonKey: string;
  isConfigured: boolean;
}

const fallbackSupabaseUrl = 'https://placeholder.bytilyst.local';
const fallbackSupabaseAnonKey = 'placeholder-anon-key';

function pickConfiguredValue(...values: Array<string | undefined>): string | undefined {
  return values.find((value) => typeof value === 'string' && value.trim().length > 0)?.trim();
}

export function getWebSupabaseConfig(): SupabaseRuntimeConfig {
  const url = pickConfiguredValue(
    process.env.NEXT_PUBLIC_SUPABASE_URL,
    process.env.VITE_SUPABASE_URL,
    process.env.VITE_PLATFORM_SUPABASE_URL,
    process.env.VITE_PUBLIC_SUPABASE_URL
  );

  const anonKey = pickConfiguredValue(
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
    process.env.VITE_SUPABASE_ANON_KEY,
    process.env.VITE_PLATFORM_SUPABASE_ANON_KEY,
    process.env.VITE_PUBLIC_SUPABASE_ANON_KEY
  );

  return {
    url: url || fallbackSupabaseUrl,
    anonKey: anonKey || fallbackSupabaseAnonKey,
    isConfigured: Boolean(url && anonKey),
  };
}

export function getMobileSupabaseConfig(): SupabaseRuntimeConfig {
  const url = pickConfiguredValue(
    process.env.EXPO_PUBLIC_SUPABASE_URL,
    process.env.EXPO_PUBLIC_PLATFORM_SUPABASE_URL,
    process.env.EXPO_PUBLIC_PUBLIC_SUPABASE_URL
  );

  const anonKey = pickConfiguredValue(
    process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY,
    process.env.EXPO_PUBLIC_PLATFORM_SUPABASE_ANON_KEY,
    process.env.EXPO_PUBLIC_PUBLIC_SUPABASE_ANON_KEY
  );

  return {
    url: url || fallbackSupabaseUrl,
    anonKey: anonKey || fallbackSupabaseAnonKey,
    isConfigured: Boolean(url && anonKey),
  };
}
