const { createClient } = require('@supabase/supabase-js');
require('dotenv').config();

/**
 * Supabase client for backend operations
 * Uses service role key for admin access
 */
const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_SERVICE_ROLE_KEY,
  {
    auth: {
      autoRefreshToken: false,
      persistSession: false
    }
  }
);

/**
 * Get Supabase client instance
 * @returns {Object} Supabase client
 */
function getSupabaseClient() {
  return supabase;
}

/**
 * Execute a raw SQL query using Supabase
 * @param {string} query - SQL query
 * @param {Array} params - Query parameters
 * @returns {Promise<Object>} Query result
 */
async function executeQuery(query, params = []) {
  try {
    const { data, error } = await supabase.rpc('execute_sql', {
      query: query,
      params: params
    });

    if (error) {
      throw error;
    }

    return { rows: data, rowCount: data?.length || 0 };
  } catch (error) {
    console.error('Supabase query error:', error);
    throw error;
  }
}

module.exports = {
  supabase,
  getSupabaseClient,
  executeQuery
};
