import { createClient } from '@supabase/supabase-js';
import fs from 'fs';
import path from 'path';

import dotenv from 'dotenv';
dotenv.config();

const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_SERVICE_KEY;

if (!supabaseUrl || !supabaseKey) {
  console.error('Missing required environment variables: SUPABASE_URL and SUPABASE_SERVICE_KEY');
  process.exit(1);
}

const supabase = createClient(supabaseUrl, supabaseKey);

async function runSQLFile(filename) {
  console.log(`Running: ${filename}`);
  
  try {
    const migrationPath = path.join(process.cwd(), 'supabase/migrations', filename);
    const sql = fs.readFileSync(migrationPath, 'utf8');
    
    // Split SQL into individual statements
    const statements = sql.split(';').filter(stmt => stmt.trim());
    
    for (const statement of statements) {
      if (statement.trim()) {
        const { error } = await supabase.rpc('exec_sql', { sql: statement.trim() + ';' });
        if (error) {
          console.error(`Error in ${filename}:`, error);
          return false;
        }
      }
    }
    
    console.log(`✓ ${filename} completed`);
    return true;
  } catch (err) {
    console.error(`Error reading ${filename}:`, err.message);
    return false;
  }
}

async function setupSchema() {
  console.log('Setting up database schema...');
  
  const migrations = [
    '001_initial_schema.sql',
    '002_add_fee_structure.sql', 
    '003_add_seating_and_ticket_types.sql',
    '004_add_admin_system.sql'
  ];
  
  for (const migration of migrations) {
    const success = await runSQLFile(migration);
    if (!success) {
      console.error(`Failed: ${migration}`);
      process.exit(1);
    }
  }
  
  console.log('✓ All migrations completed!');
}

setupSchema().catch(console.error);