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

let supabase: SupabaseClient | null = null;

export const getSupabaseClient = (): SupabaseClient => {
  if (!supabase) {
    const supabaseUrl = config.supabase?.url;
    const supabaseKey = config.supabase?.anonKey;

    if (!supabaseUrl || !supabaseKey) {
      logger.warn('Supabase credentials not configured, some features may not work');
      throw new Error('Supabase configuration missing');
    }

    supabase = createClient(supabaseUrl, supabaseKey);
    logger.info('Supabase client initialized');
  }

  return supabase;
};

export const getSupabaseServiceClient = (): SupabaseClient => {
  const supabaseUrl = config.supabase?.url;
  const supabaseServiceKey = config.supabase?.serviceKey;

  if (!supabaseUrl || !supabaseServiceKey) {
    logger.warn('Supabase service credentials not configured');
    throw new Error('Supabase service configuration missing');
  }

  return createClient(supabaseUrl, supabaseServiceKey);
};

// Test connection function
export const testSupabaseConnection = async (): Promise<boolean> => {
  try {
    const client = getSupabaseClient();
    const { error } = await client.from('_health_check').select('*').limit(1);
    
    // If the table doesn't exist, that's fine - we just tested the connection
    if (error && !error.message.includes('relation "_health_check" does not exist')) {
      logger.error('Supabase connection test failed:', error);
      return false;
    }
    
    logger.info('Supabase connection test successful');
    return true;
  } catch (error) {
    logger.error('Supabase connection test failed:', error);
    return false;
  }
};

export default getSupabaseClient;