#!/usr/bin/env node

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

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

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 SUPABASE_URL or SUPABASE_SERVICE_KEY environment variables');
  process.exit(1);
}

const supabase = createClient(supabaseUrl, supabaseKey);

async function runMigration(filename) {
  console.log(`Running migration: ${filename}`);
  
  try {
    const migrationPath = path.join(__dirname, 'supabase/migrations', filename);
    const migrationSQL = fs.readFileSync(migrationPath, 'utf8');
    
    // Execute the migration using raw SQL
    const { error } = await supabase.rpc('exec_sql', { sql: migrationSQL });
    
    if (error) {
      console.error(`Error running migration ${filename}:`, error);
      return false;
    }
    
    console.log(`✓ Migration ${filename} completed successfully`);
    return true;
  } catch (err) {
    console.error(`Error reading migration ${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',
    '005_add_fee_payment_model.sql',
    '006_standardize_bct_fees.sql',
    '007_add_premium_addons.sql',
    '008_add_featured_events_support.sql',
    '009_add_printed_tickets.sql',
    '010_add_scanner_lock.sql',
    '20250708_add_event_image_support.sql',
    '20250708_add_marketing_kit_support.sql',
    '20250708_add_referral_tracking.sql',
    '20250708_add_social_media_links.sql',
    '20250109_territory_manager_schema.sql',
    '20250109_onboarding_system.sql',
    '20250109_kiosk_pin_system.sql',
    '20250109_codereadr_integration.sql',
    '20250109_add_sample_territories.sql',
    '20250110_custom_sales_pages.sql'
  ];
  
  for (const migration of migrations) {
    const success = await runMigration(migration);
    if (!success) {
      console.error(`Failed to run migration: ${migration}`);
      process.exit(1);
    }
  }
  
  console.log('✓ All migrations completed successfully!');
}

setupSchema().catch(console.error);