import { createClient, SupabaseClient } from '@supabase/supabase-js';
import { logger } from './debugConfig';

const rawSupabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;

// Same-origin proxy support: a leading-slash value (e.g. "/__supabase") is
// resolved against the current browser origin so supabase-js receives an
// absolute URL while every request stays same-origin (no CORS) and routes
// through the app host's /__supabase nginx proxy to the backend Supabase.
const supabaseUrl = rawSupabaseUrl?.startsWith('/')
  ? `${window.location.origin}${rawSupabaseUrl}`
  : rawSupabaseUrl;

if (!supabaseUrl || !supabaseAnonKey) {
  throw new Error('Missing Supabase configuration');
}

logger.info('supabase-client', '🔄 Initializing Supabase client', {
  url: supabaseUrl,
  hasKey: !!supabaseAnonKey,
});

export const supabase: SupabaseClient = createClient(
  supabaseUrl,
  supabaseAnonKey,
  {
    auth: {
      flowType: 'pkce',
      autoRefreshToken: true,
      persistSession: true,
      detectSessionInUrl: false,
      storage: window.localStorage,
      storageKey: 'supabase.auth.token',
      debug: true
    },
    global: {
      headers: {
        'X-Client-Info': 'classroom-copilot',
      },
    },
    db: {
      schema: 'public'
    }
  }
);