/**
 * Client-side Supabase configuration with enhanced security
 * 
 * IMPORTANT: This module does NOT export a singleton instance.
 * Always use createClient() to get a fresh client instance.
 * This prevents stale auth credentials on shared devices.
 */

import { createClient as createSupabaseClient, SupabaseClient } from '@supabase/supabase-js'

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!

/**
 * Creates a fresh Supabase client instance.
 * 
 * IMPORTANT: Call this function each time you need a client to ensure
 * fresh auth state. Do NOT cache the returned client - shared devices
 * can have multiple users and caching leads to stale auth credentials.
 * 
 * @returns A new Supabase client instance with current auth state
 */
export function createClient(): SupabaseClient {
  return createSupabaseClient(supabaseUrl, supabaseAnonKey, {
    auth: {
      persistSession: true,
      autoRefreshToken: true,
      detectSessionInUrl: true,
      flowType: 'pkce',
    },
    global: {
      headers: {
        'X-Client-Info': 'rateright-v2/1.0.0',
      },
    },
  })
}

/**
 * @deprecated Use createClient() instead. This export will be removed.
 * Direct supabase export is disabled to prevent stale auth on shared devices.
 * Always call createClient() to get a fresh instance.
 */
export const supabase = new Proxy({} as SupabaseClient, {
  get() {
    throw new Error(
      'Direct supabase import is deprecated and disabled for security. ' +
      'Use createClient() instead to prevent stale auth on shared devices.'
    )
  },
})
