import { createClient } from '@supabase/supabase-js';
import dotenv from 'dotenv';
dotenv.config();

const supabaseUrl = process.env.SUPABASE_URL;
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;

if (!supabaseUrl || !supabaseServiceKey) {
  throw new Error('❌ SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY must be provided in environment variables');
}

export const GPI_SCHEMA = 'gpi';

export const supabase = createClient(supabaseUrl, supabaseServiceKey, {
  db: {
    schema: GPI_SCHEMA
  },
  auth: {
    autoRefreshToken: false,
    persistSession: false
  }
});

export async function queryGpi(table: string, query?: any) {
  let dbQuery = supabase.from(table).select('*');
  
  if (query) {
    if (query.filter) {
      Object.entries(query.filter).forEach(([key, value]) => {
        dbQuery = dbQuery.eq(key, value);
      });
    }
    if (query.order) {
      dbQuery = dbQuery.order(query.order.by || 'created_at', { ascending: query.order.asc ?? false });
    }
    if (query.limit) {
      dbQuery = dbQuery.limit(query.limit);
    }
    if (query.offset) {
      dbQuery = dbQuery.range(query.offset, query.offset + (query.limit || 10) - 1);
    }
  }
  
  return await dbQuery;
}

export async function insertGpi(table: string, data: any) {
  return await supabase.from(table).insert(data).select();
}

export async function updateGpi(table: string, id: string, data: any) {
  return await supabase.from(table).update(data).eq('id', id).select();
}

export async function deleteGpi(table: string, id: string) {
  return await supabase.from(table).delete().eq('id', id);
}

export async function findOneGpi(table: string, filters: Record<string, any>) {
  let query = supabase.from(table).select('*');
  
  Object.entries(filters).forEach(([key, value]) => {
    query = query.eq(key, value);
  });
  
  const { data, error } = await query.single();
  
  if (error && error.code !== 'PGRST116') {
    throw error;
  }
  
  return data;
}
