const { Pool } = require('pg');
const fs = require('fs');
const path = require('path');

// Database configuration
const poolConfig = process.env.DATABASE_URL 
  ? { connectionString: process.env.DATABASE_URL }
  : {
      host: process.env.DB_HOST,
      port: process.env.DB_PORT,
      database: process.env.DB_NAME,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
    };

const pool = new Pool({
  ...poolConfig,
  max: 1,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 10000,
});

async function runMigrations() {
  console.log('Starting database migrations...');
  
  try {
    // Test connection first
    const client = await pool.connect();
    console.log('✅ Database connection successful');
    
    // Create migrations table if it doesn't exist
    await client.query(`
      CREATE TABLE IF NOT EXISTS migrations (
        id VARCHAR(255) PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        executed_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
      );
    `);
    console.log('✅ Migrations table created or already exists');
    
    // Get migration files
    const migrationsDir = path.join(__dirname, '../src/models/migrations');
    const files = fs.readdirSync(migrationsDir)
      .filter(file => file.endsWith('.sql'))
      .sort();
    
    console.log(`Found ${files.length} migration files`);
    
    for (const file of files) {
      const migrationId = file.replace('.sql', '');
      
      // Check if migration already executed
      const { rows } = await client.query('SELECT id FROM migrations WHERE id = $1', [migrationId]);
      
      if (rows.length > 0) {
        console.log(`⏭️  Migration ${migrationId} already executed, skipping`);
        continue;
      }
      
      // Load and execute migration
      const filePath = path.join(migrationsDir, file);
      const sql = fs.readFileSync(filePath, 'utf-8');
      
      console.log(`🔄 Executing migration: ${migrationId}`);
      await client.query(sql);
      
      // Mark as executed
      await client.query('INSERT INTO migrations (id, name) VALUES ($1, $2)', [migrationId, file]);
      console.log(`✅ Migration ${migrationId} completed`);
    }
    
    client.release();
    await pool.end();
    
    console.log('🎉 All migrations completed successfully!');
    
  } catch (error) {
    console.error('❌ Migration failed:', error.message);
    console.error('Error details:', error);
    process.exit(1);
  }
}

runMigrations(); 