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

async function createMigrationsTable() {
  await database.query(`
    CREATE TABLE IF NOT EXISTS schema_migrations (
      version VARCHAR(255) PRIMARY KEY,
      applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      service VARCHAR(100) DEFAULT 'unified-tech-stack-service'
    )
  `);
}

async function isMigrationApplied(version) {
  const result = await database.query(
    'SELECT version FROM schema_migrations WHERE version = $1 AND service = $2',
    [version, 'unified-tech-stack-service']
  );
  return result.rows.length > 0;
}

async function markMigrationApplied(version) {
  await database.query(
    'INSERT INTO schema_migrations (version, service) VALUES ($1, $2) ON CONFLICT (version) DO NOTHING',
    [version, 'unified-tech-stack-service']
  );
}

async function runMigrations() {
  console.log('🚀 Starting unified-tech-stack-service database migrations...');

  try {
    // Create migrations tracking table first
    await createMigrationsTable();
    console.log('✅ Migration tracking table ready');

    // Get all migration files in order
    const migrationFiles = [
      '001_unified_tech_stack_recommendations.sql'
    ];

    let appliedCount = 0;
    let skippedCount = 0;

    for (const migrationFile of migrationFiles) {
      const migrationPath = path.join(__dirname, migrationFile);

      // Check if migration file exists
      if (!fs.existsSync(migrationPath)) {
        console.log(`⚠️ Migration file not found: ${migrationFile}`);
        continue;
      }

      // Check if migration was already applied
      if (await isMigrationApplied(migrationFile)) {
        console.log(`⏭️  Migration ${migrationFile} already applied, skipping...`);
        skippedCount++;
        continue;
      }

      const migrationSQL = fs.readFileSync(migrationPath, 'utf8');

      // Skip destructive migrations unless explicitly allowed
      const containsDrop = /\bdrop\s+table\b/i.test(migrationSQL);
      const allowDestructiveEnv = String(process.env.ALLOW_DESTRUCTIVE_MIGRATIONS || '').toLowerCase() === 'true';

      if (containsDrop && !allowDestructiveEnv) {
        console.log(`⏭️  Skipping potentially destructive migration (set ALLOW_DESTRUCTIVE_MIGRATIONS=true to run): ${migrationFile}`);
        skippedCount++;
        continue;
      }

      console.log(`📄 Running migration: ${migrationFile}`);

      // Execute the migration
      await database.query(migrationSQL);
      await markMigrationApplied(migrationFile);

      console.log(`✅ Migration ${migrationFile} completed!`);
      appliedCount++;
    }

    console.log(`📊 Migration summary: ${appliedCount} applied, ${skippedCount} skipped`);

    // Verify tables were created
    const result = await database.query(`
      SELECT table_name 
      FROM information_schema.tables 
      WHERE table_schema = 'public' 
      AND table_name IN ('tech_stack_recommendations')
      ORDER BY table_name
    `);

    console.log('🔍 Verified tables:', result.rows.map(row => row.table_name));

    // Check if users table exists (dependency from user-auth service)
    const usersCheck = await database.query(`
      SELECT table_name 
      FROM information_schema.tables 
      WHERE table_schema = 'public' 
      AND table_name = 'users'
    `);

    if (usersCheck.rows.length > 0) {
      console.log('✅ Users table found (user-auth service dependency satisfied)');
    } else {
      console.log('⚠️  Users table not found - make sure user-auth service migrations have been run');
    }

    // Test the new functions
    console.log('🧪 Testing database functions...');
    
    try {
      // Test cleanup function
      const cleanupResult = await database.query('SELECT cleanup_expired_recommendations()');
      console.log('✅ cleanup_expired_recommendations() function working');
      
      // Test user stats function (with a dummy UUID)
      const statsResult = await database.query('SELECT * FROM get_user_recommendation_stats($1)', ['00000000-0000-0000-0000-000000000000']);
      console.log('✅ get_user_recommendation_stats() function working');
      
      console.log('✅ All database functions are working correctly');
    } catch (funcError) {
      console.log('⚠️  Some database functions may not be working:', funcError.message);
    }

  } catch (error) {
    console.error('❌ Migration failed:', error.message);
    console.error('📍 Error details:', error);
    process.exit(1);
  } finally {
    await database.close();
  }
}

// Run migration if called directly
if (require.main === module) {
  runMigrations();
}

module.exports = { runMigrations };
