const fs = require('fs');
const path = require('path');
const database = require('../config/database');

const migrationsDir = path.join(__dirname);

async function runMigrations() {
  console.log('🚀 Starting Git Integration database migration...');

  try {
    // Connect to database
    await database.testConnection();
    console.log('✅ Database connected successfully');

    // Get list of migration files (skip the tracking system as it's handled by main migration)
    const migrationFiles = fs.readdirSync(migrationsDir)
      .filter(file => file.endsWith('.sql') && file !== '000_migration_tracking_system.sql')
      .sort();

    console.log(`📄 Found ${migrationFiles.length} migration files:`, migrationFiles);

    for (const migrationFile of migrationFiles) {
      const migrationVersion = migrationFile.replace('.sql', '');
      
      // Check if migration already applied
      const existingMigration = await database.query(
        'SELECT version FROM schema_migrations WHERE version = $1 AND service = $2',
        [migrationVersion, 'git-integration']
      );
      
      if (existingMigration.rows.length > 0) {
        console.log(`⏭️  Skipping already applied migration: ${migrationFile}`);
        continue;
      }
      
      console.log(`🚀 Running migration: ${migrationFile}`);

      const migrationPath = path.join(migrationsDir, migrationFile);
      const migrationSQL = fs.readFileSync(migrationPath, 'utf8');

      try {
        await database.query(migrationSQL);
        
        // Record migration in main schema_migrations table
        await database.query(
          'INSERT INTO schema_migrations (version, service) VALUES ($1, $2) ON CONFLICT (version) DO NOTHING',
          [migrationFile.replace('.sql', ''), 'git-integration']
        );
        
        console.log(`✅ Migration ${migrationFile} completed successfully!`);
      } catch (err) {
        const message = (err && err.message) ? err.message.toLowerCase() : '';
        const code = err && err.code ? err.code : '';
        // Continue on idempotency-safe errors (objects already exist)
        const isIdempotentError =
          message.includes('already exists') ||
          code === '42710' /* duplicate_object */ ||
          code === '42P07' /* duplicate_table */ ||
          code === '42701' /* duplicate_column */ ||
          code === '42P06' /* duplicate_schema */ ||
          code === '42723' /* duplicate_function */;

        if (isIdempotentError) {
          console.warn(`⚠️  Skipping idempotent error for ${migrationFile}:`, err.message);
          continue;
        }

        throw err; // rethrow non-idempotent errors
      }
    }

    // Verify tables were created
    const tablesQuery = `
      SELECT table_name 
      FROM information_schema.tables 
      WHERE table_schema = 'public' 
      AND table_name NOT LIKE 'pg_%'
      ORDER BY table_name
    `;

    const tablesResult = await database.query(tablesQuery);
    const tableNames = tablesResult.rows.map(row => row.table_name);

    console.log('🔍 Verified tables:', tableNames);
    console.log('🎉 All migrations completed successfully!');
    
  } catch (error) {
    console.error('❌ Migration failed:', error);
    process.exit(1);
  } finally {
    await database.close();
    console.log('🔌 Database connection closed');
  }
}

// Run migrations if this file is executed directly
if (require.main === module) {
  runMigrations();
}

module.exports = { runMigrations };
