/**
 * migrate.js
 * Database migration runner
 */

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import sequelize from '../config/database.js';

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

const runMigrations = async () => {
  try {
    console.log('[Migrate] Connecting to database...');
    await sequelize.authenticate();
    console.log('[Migrate] Database connection established');

    // Create migrations tracking table if it doesn't exist
    await sequelize.query(`
      CREATE TABLE IF NOT EXISTS migrations (
        id SERIAL PRIMARY KEY,
        name VARCHAR(255) UNIQUE NOT NULL,
        executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      );
    `);

    // Get list of migration files
    const migrationsDir = path.join(__dirname, '../../migrations');
    const migrationFiles = fs.readdirSync(migrationsDir)
      .filter(file => file.endsWith('.js'))
      .sort(); // Sort by filename (which includes timestamp)

    // Get already executed migrations
    const [executedMigrations] = await sequelize.query(
      'SELECT name FROM migrations ORDER BY name'
    );
    const executedNames = executedMigrations.map(m => m.name);

    console.log(`[Migrate] Found ${migrationFiles.length} migration files`);
    console.log(`[Migrate] Already executed: ${executedNames.length} migrations`);

    // Run pending migrations
    for (const file of migrationFiles) {
      const migrationName = file.replace('.js', '');

      if (executedNames.includes(migrationName)) {
        console.log(`[Migrate] ✓ ${migrationName} (already executed)`);
        continue;
      }

      console.log(`[Migrate] → Running ${migrationName}...`);

      try {
        // Import and run migration
        const migrationPath = path.join(migrationsDir, file);
        const migration = await import(migrationPath);

        if (!migration.default || !migration.default.up) {
          throw new Error(`Migration ${file} does not export a valid up() function`);
        }

        // Run the migration
        await migration.default.up(sequelize.getQueryInterface());

        // Record successful execution
        await sequelize.query(
          'INSERT INTO migrations (name) VALUES (?)',
          { replacements: [migrationName] }
        );

        console.log(`[Migrate] ✓ ${migrationName} completed successfully`);
      } catch (error) {
        console.error(`[Migrate] ✗ ${migrationName} failed:`, error.message);
        throw error;
      }
    }

    console.log('[Migrate] All migrations completed successfully');
    await sequelize.close();
    process.exit(0);
  } catch (error) {
    console.error('[Migrate] Migration failed:', error);
    await sequelize.close();
    process.exit(1);
  }
};

runMigrations();
