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 (
      id SERIAL PRIMARY KEY,
      version VARCHAR(255) NOT NULL UNIQUE,
      service VARCHAR(100) NOT NULL,
      applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      description TEXT
    )
  `);
}

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

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

async function runMigrations() {
  console.log('🚀 Starting AI Mockup Service database migrations...');
  
  const migrations = [
    {
      file: '001_wireframe_schema.sql',
      version: '001_wireframe_schema',
      description: 'Create wireframe-related tables'
    }
  ];
  
  try {
    // Ensure required extensions exist before running migrations
    console.log('🔧 Ensuring required PostgreSQL extensions...');
    await database.query('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";');
    console.log('✅ Extensions ready');

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

    let appliedCount = 0;
    let skippedCount = 0;

    for (const migration of migrations) {
      const migrationPath = path.join(__dirname, migration.file);
      if (!fs.existsSync(migrationPath)) {
        console.warn(`⚠️ Migration file ${migration.file} not found, skipping...`);
        continue;
      }

      // Check if migration was already applied
      if (await isMigrationApplied(migration.version)) {
        console.log(`⏭️  Migration ${migration.file} already applied, skipping...`);
        skippedCount++;
        continue;
      }
      
      const migrationSQL = fs.readFileSync(migrationPath, 'utf8');
      console.log(`📄 Running migration: ${migration.file}`);
      
      await database.query(migrationSQL);
      await markMigrationApplied(migration.version, migration.description);
      console.log(`✅ Migration ${migration.file} completed!`);
      appliedCount++;
    }
    
    console.log(`📊 Migration summary: ${appliedCount} applied, ${skippedCount} skipped`);
    
    // Verify all tables
    const result = await database.query(`
      SELECT 
        schemaname,
        tablename,
        tableowner
      FROM pg_tables 
      WHERE schemaname = 'public' 
      AND tablename IN ('wireframes', 'wireframe_versions', 'wireframe_elements')
      ORDER BY tablename
    `);
    
    console.log('🔍 Verified tables:');
    result.rows.forEach(row => {
      console.log(`  - ${row.tablename}`);
    });
    
    console.log('✅ AI Mockup Service migrations completed successfully!');
    process.exit(0);
  } catch (error) {
    console.error('❌ Migration failed:', error.message);
    console.error('📚 Error details:', error);
    process.exit(1);
  }
}

runMigrations();
