/**
 * Enhanced Migrations Generator
 * Generates comprehensive database migration infrastructure
 *
 * Features:
 * - Multi-ORM support (Prisma, Drizzle, TypeORM, Knex)
 * - Migration versioning strategies
 * - Rollback capabilities
 * - Data migrations
 * - Seeding infrastructure
 * - Migration validation
 * - CI/CD integration
 */

import { GeneratorContext, GeneratedFile, GenerationResult } from '../types';
import { Migrations } from '../../types/workflow';
import * as path from 'path';

export class EnhancedMigrationsGenerator {
  readonly id = 'enhanced-migrations';
  readonly name = 'Enhanced Migrations Generator';
  readonly description = 'Generates comprehensive database migration infrastructure with multi-ORM support';

  generate(context: GeneratorContext): GenerationResult {
    const { workflow, outputDirectory } = context;
    const files: GeneratedFile[] = [];

    if (!workflow.migrations) {
      return { files };
    }

    const migrations = workflow.migrations;
    const strategy = migrations.strategy || 'prisma_migrate';

    // Generate migration configuration
    files.push(this.generateMigrationConfig(migrations, strategy, outputDirectory));

    // Generate migration scripts based on strategy
    switch (strategy) {
      case 'prisma_migrate':
        files.push(...this.generatePrismaMigrations(migrations, outputDirectory));
        break;
      case 'drizzle':
        files.push(...this.generateDrizzleMigrations(migrations, outputDirectory));
        break;
      case 'typeorm':
        files.push(...this.generateTypeORMMigrations(migrations, outputDirectory));
        break;
      case 'knex':
        files.push(...this.generateKnexMigrations(migrations, outputDirectory));
        break;
      case 'custom':
        files.push(...this.generateCustomMigrations(migrations, outputDirectory));
        break;
    }

    // Generate common migration utilities
    files.push(this.generateMigrationRunner(migrations, strategy, outputDirectory));
    files.push(this.generateMigrationValidator(migrations, strategy, outputDirectory));
    files.push(this.generateDataMigrationTemplate(migrations, outputDirectory));
    files.push(this.generateRollbackScript(migrations, strategy, outputDirectory));
    files.push(this.generateMigrationCLI(migrations, strategy, outputDirectory));

    return { files };
  }

  private generateMigrationConfig(migrations: Migrations, strategy: string, outputDirectory: string): GeneratedFile {
    const content = `/**
 * Migration Configuration
 * Generated by Bangstack
 */

export const migrationConfig = {
  strategy: '${strategy}',
  autoGenerate: ${migrations.auto_generate !== false},
  versionControl: {
    naming: '${migrations.version_control?.naming || 'timestamp'}',
  },
  paths: {
    migrations: './migrations',
    seeds: './seeds',
    backups: './backups',
  },
  database: {
    // Database connection is managed by your ORM configuration
  },
  options: {
    // Validate migrations before running
    validateBeforeRun: true,
    // Create backup before running migrations
    backupBeforeRun: process.env.NODE_ENV === 'production',
    // Lock table to prevent concurrent migrations
    useLocking: true,
    // Transaction mode
    transactional: true,
  },
};

export default migrationConfig;
`;

    return {
      path: path.join(outputDirectory, 'api/src/config/migrations.ts'),
      content,
    };
  }

  private generatePrismaMigrations(migrations: Migrations, outputDirectory: string): GeneratedFile[] {
    const files: GeneratedFile[] = [];

    // Prisma migration helper
    files.push({
      path: path.join(outputDirectory, 'api/src/db/prisma-migrations.ts'),
      content: `/**
 * Prisma Migration Helper
 * Generated by Bangstack
 */

import { PrismaClient } from '@prisma/client';
import { exec } from 'child_process';
import { promisify } from 'util';

const execAsync = promisify(exec);
const prisma = new PrismaClient();

export class PrismaMigrationRunner {
  /**
   * Run pending migrations
   */
  async migrate(): Promise<void> {
    console.log('Running Prisma migrations...');

    try {
      const { stdout, stderr } = await execAsync('npx prisma migrate deploy');
      console.log(stdout);
      if (stderr) console.error(stderr);
    } catch (error) {
      console.error('Migration failed:', error);
      throw error;
    }
  }

  /**
   * Generate a new migration
   */
  async generateMigration(name: string): Promise<void> {
    console.log(\`Generating migration: \${name}\`);

    try {
      const { stdout, stderr } = await execAsync(\`npx prisma migrate dev --name \${name}\`);
      console.log(stdout);
      if (stderr) console.error(stderr);
    } catch (error) {
      console.error('Migration generation failed:', error);
      throw error;
    }
  }

  /**
   * Check migration status
   */
  async status(): Promise<void> {
    try {
      const { stdout } = await execAsync('npx prisma migrate status');
      console.log(stdout);
    } catch (error) {
      console.error('Failed to check migration status:', error);
      throw error;
    }
  }

  /**
   * Reset database (development only)
   */
  async reset(): Promise<void> {
    if (process.env.NODE_ENV === 'production') {
      throw new Error('Cannot reset database in production');
    }

    console.log('Resetting database...');

    try {
      const { stdout, stderr } = await execAsync('npx prisma migrate reset --force');
      console.log(stdout);
      if (stderr) console.error(stderr);
    } catch (error) {
      console.error('Database reset failed:', error);
      throw error;
    }
  }
}

export const prismaMigrations = new PrismaMigrationRunner();
`,
    });

    return files;
  }

  private generateDrizzleMigrations(migrations: Migrations, outputDirectory: string): GeneratedFile[] {
    const files: GeneratedFile[] = [];

    files.push({
      path: path.join(outputDirectory, 'api/src/db/drizzle-migrations.ts'),
      content: `/**
 * Drizzle Migration Helper
 * Generated by Bangstack
 */

import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import * as path from 'path';

export class DrizzleMigrationRunner {
  private pool: Pool;
  private db: ReturnType<typeof drizzle>;

  constructor() {
    this.pool = new Pool({
      connectionString: process.env.DATABASE_URL,
    });
    this.db = drizzle(this.pool);
  }

  /**
   * Run pending migrations
   */
  async migrate(): Promise<void> {
    console.log('Running Drizzle migrations...');

    try {
      await migrate(this.db, {
        migrationsFolder: path.join(__dirname, '../../migrations'),
      });
      console.log('Migrations completed successfully');
    } catch (error) {
      console.error('Migration failed:', error);
      throw error;
    }
  }

  /**
   * Close database connection
   */
  async close(): Promise<void> {
    await this.pool.end();
  }
}

export const drizzleMigrations = new DrizzleMigrationRunner();
`,
    });

    // Drizzle config
    files.push({
      path: path.join(outputDirectory, 'drizzle.config.ts'),
      content: `/**
 * Drizzle Configuration
 * Generated by Bangstack
 */

import type { Config } from 'drizzle-kit';

export default {
  schema: './api/src/db/schema.ts',
  out: './migrations',
  driver: 'pg',
  dbCredentials: {
    connectionString: process.env.DATABASE_URL || '',
  },
  verbose: true,
  strict: true,
} satisfies Config;
`,
    });

    return files;
  }

  private generateTypeORMMigrations(_migrations: Migrations, outputDirectory: string): GeneratedFile[] {
    const files: GeneratedFile[] = [];

    files.push({
      path: path.join(outputDirectory, 'api/src/db/typeorm-migrations.ts'),
      content: `/**
 * TypeORM Migration Helper
 * Generated by Bangstack
 */

import { DataSource } from 'typeorm';
import * as path from 'path';

export class TypeORMMigrationRunner {
  private dataSource: DataSource;

  constructor() {
    this.dataSource = new DataSource({
      type: 'postgres',
      url: process.env.DATABASE_URL,
      entities: [path.join(__dirname, '../entities/**/*.ts')],
      migrations: [path.join(__dirname, '../../migrations/**/*.ts')],
      synchronize: false,
      logging: true,
    });
  }

  /**
   * Initialize data source
   */
  async initialize(): Promise<void> {
    if (!this.dataSource.isInitialized) {
      await this.dataSource.initialize();
    }
  }

  /**
   * Run pending migrations
   */
  async migrate(): Promise<void> {
    console.log('Running TypeORM migrations...');

    try {
      await this.initialize();
      await this.dataSource.runMigrations();
      console.log('Migrations completed successfully');
    } catch (error) {
      console.error('Migration failed:', error);
      throw error;
    }
  }

  /**
   * Rollback last migration
   */
  async rollback(): Promise<void> {
    console.log('Rolling back last migration...');

    try {
      await this.initialize();
      await this.dataSource.undoLastMigration();
      console.log('Rollback completed successfully');
    } catch (error) {
      console.error('Rollback failed:', error);
      throw error;
    }
  }

  /**
   * Generate a new migration
   */
  async generateMigration(name: string): Promise<void> {
    console.log(\`Generating migration: \${name}\`);

    try {
      await this.initialize();
      // Note: This requires typeorm CLI
      console.log('Use: npx typeorm migration:generate ./migrations/' + name);
    } catch (error) {
      console.error('Migration generation failed:', error);
      throw error;
    }
  }

  /**
   * Close connection
   */
  async close(): Promise<void> {
    if (this.dataSource.isInitialized) {
      await this.dataSource.destroy();
    }
  }
}

export const typeormMigrations = new TypeORMMigrationRunner();
`,
    });

    return files;
  }

  private generateKnexMigrations(_migrations: Migrations, outputDirectory: string): GeneratedFile[] {
    const files: GeneratedFile[] = [];

    files.push({
      path: path.join(outputDirectory, 'api/src/db/knex-migrations.ts'),
      content: `/**
 * Knex Migration Helper
 * Generated by Bangstack
 */

import knex, { Knex } from 'knex';
import * as path from 'path';

export class KnexMigrationRunner {
  private knex: Knex;

  constructor() {
    this.knex = knex({
      client: 'pg',
      connection: process.env.DATABASE_URL,
      migrations: {
        directory: path.join(__dirname, '../../migrations'),
        tableName: 'knex_migrations',
        extension: 'ts',
      },
      seeds: {
        directory: path.join(__dirname, '../../seeds'),
      },
    });
  }

  /**
   * Run pending migrations
   */
  async migrate(): Promise<void> {
    console.log('Running Knex migrations...');

    try {
      const [batch, log] = await this.knex.migrate.latest();

      if (log.length === 0) {
        console.log('Already up to date');
      } else {
        console.log(\`Batch \${batch} run: \${log.length} migrations\`);
        log.forEach(migration => console.log(\`  - \${migration}\`));
      }
    } catch (error) {
      console.error('Migration failed:', error);
      throw error;
    }
  }

  /**
   * Rollback last batch
   */
  async rollback(): Promise<void> {
    console.log('Rolling back last batch...');

    try {
      const [batch, log] = await this.knex.migrate.rollback();

      if (log.length === 0) {
        console.log('Already at the base migration');
      } else {
        console.log(\`Batch \${batch} rolled back: \${log.length} migrations\`);
        log.forEach(migration => console.log(\`  - \${migration}\`));
      }
    } catch (error) {
      console.error('Rollback failed:', error);
      throw error;
    }
  }

  /**
   * Get migration status
   */
  async status(): Promise<void> {
    try {
      const [completed, pending] = await Promise.all([
        this.knex.migrate.list(),
      ]);

      console.log('Completed migrations:', completed);
    } catch (error) {
      console.error('Failed to get migration status:', error);
      throw error;
    }
  }

  /**
   * Close connection
   */
  async close(): Promise<void> {
    await this.knex.destroy();
  }
}

export const knexMigrations = new KnexMigrationRunner();
`,
    });

    // Knexfile
    files.push({
      path: path.join(outputDirectory, 'knexfile.ts'),
      content: `/**
 * Knex Configuration
 * Generated by Bangstack
 */

import type { Knex } from 'knex';
import * as path from 'path';

const config: { [key: string]: Knex.Config } = {
  development: {
    client: 'postgresql',
    connection: process.env.DATABASE_URL || {
      host: process.env.DB_HOST || 'localhost',
      port: parseInt(process.env.DB_PORT || '5432'),
      database: process.env.DB_NAME || 'dev',
      user: process.env.DB_USER || 'postgres',
      password: process.env.DB_PASSWORD || 'postgres',
    },
    pool: {
      min: 2,
      max: 10,
    },
    migrations: {
      directory: path.join(__dirname, 'migrations'),
      tableName: 'knex_migrations',
      extension: 'ts',
    },
    seeds: {
      directory: path.join(__dirname, 'seeds'),
    },
  },

  staging: {
    client: 'postgresql',
    connection: process.env.DATABASE_URL,
    pool: {
      min: 2,
      max: 10,
    },
    migrations: {
      directory: path.join(__dirname, 'migrations'),
      tableName: 'knex_migrations',
    },
  },

  production: {
    client: 'postgresql',
    connection: process.env.DATABASE_URL,
    pool: {
      min: 2,
      max: 10,
    },
    migrations: {
      directory: path.join(__dirname, 'migrations'),
      tableName: 'knex_migrations',
    },
  },
};

export default config;
`,
    });

    return files;
  }

  private generateCustomMigrations(_migrations: Migrations, outputDirectory: string): GeneratedFile[] {
    const files: GeneratedFile[] = [];

    files.push({
      path: path.join(outputDirectory, 'api/src/db/custom-migrations.ts'),
      content: `/**
 * Custom Migration Framework
 * Generated by Bangstack
 */

import * as fs from 'fs';
import * as path from 'path';

export interface Migration {
  version: string;
  name: string;
  up: () => Promise<void>;
  down: () => Promise<void>;
}

export class CustomMigrationRunner {
  private migrationsPath: string;
  private migrations: Migration[] = [];

  constructor() {
    this.migrationsPath = path.join(__dirname, '../../migrations');
  }

  /**
   * Load all migration files
   */
  async loadMigrations(): Promise<void> {
    const files = fs.readdirSync(this.migrationsPath)
      .filter(f => f.endsWith('.ts') || f.endsWith('.js'))
      .sort();

    for (const file of files) {
      const migration = await import(path.join(this.migrationsPath, file));
      this.migrations.push(migration.default || migration);
    }
  }

  /**
   * Run all pending migrations
   */
  async migrate(): Promise<void> {
    await this.loadMigrations();

    console.log(\`Running \${this.migrations.length} migrations...\`);

    for (const migration of this.migrations) {
      try {
        console.log(\`  Running: \${migration.name}\`);
        await migration.up();
        console.log(\`  ✓ Completed: \${migration.name}\`);
      } catch (error) {
        console.error(\`  ✗ Failed: \${migration.name}\`, error);
        throw error;
      }
    }

    console.log('All migrations completed successfully');
  }

  /**
   * Rollback last migration
   */
  async rollback(): Promise<void> {
    await this.loadMigrations();

    const lastMigration = this.migrations[this.migrations.length - 1];

    if (!lastMigration) {
      console.log('No migrations to rollback');
      return;
    }

    try {
      console.log(\`Rolling back: \${lastMigration.name}\`);
      await lastMigration.down();
      console.log(\`✓ Rolled back: \${lastMigration.name}\`);
    } catch (error) {
      console.error(\`✗ Rollback failed: \${lastMigration.name}\`, error);
      throw error;
    }
  }
}

export const customMigrations = new CustomMigrationRunner();
`,
    });

    // Example custom migration template
    files.push({
      path: path.join(outputDirectory, 'migrations/example_migration.ts.template'),
      content: `/**
 * Example Migration
 * Generated by Bangstack
 *
 * Rename this file following the pattern: YYYYMMDDHHMMSS_description.ts
 */

export default {
  version: '20240101000000',
  name: 'example_migration',

  async up() {
    // Write your migration logic here
    console.log('Running up migration...');

    // Example: Create a table
    // await db.query(\`
    //   CREATE TABLE example (
    //     id SERIAL PRIMARY KEY,
    //     name VARCHAR(255) NOT NULL,
    //     created_at TIMESTAMP DEFAULT NOW()
    //   )
    // \`);
  },

  async down() {
    // Write your rollback logic here
    console.log('Running down migration...');

    // Example: Drop a table
    // await db.query('DROP TABLE IF EXISTS example');
  },
};
`,
    });

    return files;
  }

  private generateMigrationRunner(migrations: Migrations, strategy: string, outputDirectory: string): GeneratedFile {
    const content = `/**
 * Migration Runner
 * Generated by Bangstack
 */

import { migrationConfig } from '../config/migrations';

${this.getImportForStrategy(strategy)}

export class MigrationRunner {
  private runner: any;

  constructor() {
    this.runner = ${this.getRunnerInstanceForStrategy(strategy)};
  }

  /**
   * Run all pending migrations
   */
  async run(): Promise<void> {
    console.log('Starting migrations...');
    console.log(\`Strategy: \${migrationConfig.strategy}\`);

    try {
      // Validate before running if enabled
      if (migrationConfig.options.validateBeforeRun) {
        console.log('Validating migrations...');
        // Add validation logic here
      }

      // Create backup if enabled
      if (migrationConfig.options.backupBeforeRun) {
        console.log('Creating backup...');
        // Add backup logic here
      }

      // Run migrations
      await this.runner.migrate();

      console.log('✓ Migrations completed successfully');
    } catch (error) {
      console.error('✗ Migration failed:', error);
      throw error;
    }
  }

  /**
   * Rollback last migration
   */
  async rollback(): Promise<void> {
    console.log('Rolling back migrations...');

    try {
      if ('rollback' in this.runner) {
        await this.runner.rollback();
        console.log('✓ Rollback completed successfully');
      } else {
        throw new Error(\`Rollback not supported for strategy: \${migrationConfig.strategy}\`);
      }
    } catch (error) {
      console.error('✗ Rollback failed:', error);
      throw error;
    }
  }

  /**
   * Get migration status
   */
  async status(): Promise<void> {
    if ('status' in this.runner) {
      await this.runner.status();
    } else {
      console.log('Status check not available for this strategy');
    }
  }

  /**
   * Close database connection
   */
  async close(): Promise<void> {
    if ('close' in this.runner) {
      await this.runner.close();
    }
  }
}

export const migrationRunner = new MigrationRunner();
`;

    return {
      path: path.join(outputDirectory, 'api/src/db/migration-runner.ts'),
      content,
    };
  }

  private getImportForStrategy(strategy: string): string {
    switch (strategy) {
      case 'prisma_migrate':
        return "import { prismaMigrations } from './prisma-migrations';";
      case 'drizzle':
        return "import { drizzleMigrations } from './drizzle-migrations';";
      case 'typeorm':
        return "import { typeormMigrations } from './typeorm-migrations';";
      case 'knex':
        return "import { knexMigrations } from './knex-migrations';";
      case 'custom':
        return "import { customMigrations } from './custom-migrations';";
      default:
        return '';
    }
  }

  private getRunnerInstanceForStrategy(strategy: string): string {
    switch (strategy) {
      case 'prisma_migrate':
        return 'prismaMigrations';
      case 'drizzle':
        return 'drizzleMigrations';
      case 'typeorm':
        return 'typeormMigrations';
      case 'knex':
        return 'knexMigrations';
      case 'custom':
        return 'customMigrations';
      default:
        return 'null';
    }
  }

  private generateMigrationValidator(_migrations: Migrations, _strategy: string, outputDirectory: string): GeneratedFile {
    const content = `/**
 * Migration Validator
 * Generated by Bangstack
 */

import * as fs from 'fs';
import * as path from 'path';

export class MigrationValidator {
  private migrationsPath: string;

  constructor(migrationsPath: string = path.join(__dirname, '../../migrations')) {
    this.migrationsPath = migrationsPath;
  }

  /**
   * Validate all migrations
   */
  async validate(): Promise<{ valid: boolean; errors: string[] }> {
    const errors: string[] = [];

    // Check if migrations directory exists
    if (!fs.existsSync(this.migrationsPath)) {
      errors.push('Migrations directory does not exist');
      return { valid: false, errors };
    }

    // Get all migration files
    const files = fs.readdirSync(this.migrationsPath)
      .filter(f => f.endsWith('.ts') || f.endsWith('.js') || f.endsWith('.sql'));

    if (files.length === 0) {
      errors.push('No migration files found');
      return { valid: false, errors };
    }

    // Validate file naming
    const validatedFiles = files.map(file => this.validateFileName(file));
    const fileErrors = validatedFiles.filter(r => !r.valid);

    if (fileErrors.length > 0) {
      errors.push(...fileErrors.map(r => r.error!));
    }

    // Check for duplicate versions
    const versions = files.map(f => this.extractVersion(f));
    const duplicates = versions.filter((v, i) => versions.indexOf(v) !== i);

    if (duplicates.length > 0) {
      errors.push(\`Duplicate migration versions found: \${duplicates.join(', ')}\`);
    }

    return {
      valid: errors.length === 0,
      errors,
    };
  }

  private validateFileName(filename: string): { valid: boolean; error?: string } {
    // Check if filename follows convention: timestamp_description.ext
    const timestampPattern = /^\\d{14}_[a-z0-9_]+\\.(ts|js|sql)$/;
    const sequentialPattern = /^\\d{3}_[a-z0-9_]+\\.(ts|js|sql)$/;

    if (!timestampPattern.test(filename) && !sequentialPattern.test(filename)) {
      return {
        valid: false,
        error: \`Invalid migration filename: \${filename}. Expected format: YYYYMMDDHHMMSS_description.ext or NNN_description.ext\`,
      };
    }

    return { valid: true };
  }

  private extractVersion(filename: string): string {
    return filename.split('_')[0];
  }
}

export const migrationValidator = new MigrationValidator();
`;

    return {
      path: path.join(outputDirectory, 'api/src/db/migration-validator.ts'),
      content,
    };
  }

  private generateDataMigrationTemplate(_migrations: Migrations, outputDirectory: string): GeneratedFile {
    const content = `/**
 * Data Migration Template
 * Generated by Bangstack
 *
 * Use this template for data migrations (as opposed to schema migrations)
 */

import { PrismaClient } from '@prisma/client'; // Adjust based on your ORM
const prisma = new PrismaClient();

export default {
  version: '20240101000000', // Replace with actual timestamp
  name: 'data_migration_example',

  async up() {
    console.log('Running data migration...');

    // Example: Update existing records
    // await prisma.user.updateMany({
    //   where: { email: { contains: '@oldomain.com' } },
    //   data: { email: /* transform email */ },
    // });

    // Example: Backfill new fields
    // const users = await prisma.user.findMany({
    //   where: { newField: null },
    // });
    //
    // for (const user of users) {
    //   await prisma.user.update({
    //     where: { id: user.id },
    //     data: { newField: /* compute value */ },
    //   });
    // }

    // Example: Migrate data to new table
    // const oldData = await prisma.oldTable.findMany();
    //
    // for (const row of oldData) {
    //   await prisma.newTable.create({
    //     data: {
    //       // Transform old data to new schema
    //     },
    //   });
    // }

    console.log('Data migration completed');
  },

  async down() {
    console.log('Rolling back data migration...');

    // Write rollback logic here
    // Note: Data rollbacks can be complex and may require backups

    console.log('Data migration rollback completed');
  },
};
`;

    return {
      path: path.join(outputDirectory, 'migrations/data_migration_template.ts.template'),
      content,
    };
  }

  private generateRollbackScript(_migrations: Migrations, _strategy: string, outputDirectory: string): GeneratedFile {
    const content = `/**
 * Migration Rollback Script
 * Generated by Bangstack
 */

import { migrationRunner } from '../db/migration-runner';

async function rollback() {
  console.log('Starting rollback...');

  try {
    // Confirm rollback in production
    if (process.env.NODE_ENV === 'production') {
      console.warn('⚠️  WARNING: Rolling back in PRODUCTION environment');
      console.log('Press Ctrl+C to cancel, or wait 10 seconds to proceed...');

      await new Promise(resolve => setTimeout(resolve, 10000));
    }

    await migrationRunner.rollback();

    console.log('✓ Rollback completed successfully');
    process.exit(0);
  } catch (error) {
    console.error('✗ Rollback failed:', error);
    process.exit(1);
  } finally {
    await migrationRunner.close();
  }
}

rollback();
`;

    return {
      path: path.join(outputDirectory, 'api/src/scripts/rollback.ts'),
      content,
    };
  }

  private generateMigrationCLI(_migrations: Migrations, _strategy: string, outputDirectory: string): GeneratedFile {
    const content = `#!/usr/bin/env node
/**
 * Migration CLI
 * Generated by Bangstack
 */

import { Command } from 'commander';
import { migrationRunner } from '../db/migration-runner';
import { migrationValidator } from '../db/migration-validator';

const program = new Command();

program
  .name('migrate')
  .description('Database migration CLI')
  .version('1.0.0');

program
  .command('up')
  .description('Run pending migrations')
  .action(async () => {
    try {
      await migrationRunner.run();
      await migrationRunner.close();
      process.exit(0);
    } catch (error) {
      console.error('Migration failed:', error);
      process.exit(1);
    }
  });

program
  .command('down')
  .description('Rollback last migration')
  .action(async () => {
    try {
      await migrationRunner.rollback();
      await migrationRunner.close();
      process.exit(0);
    } catch (error) {
      console.error('Rollback failed:', error);
      process.exit(1);
    }
  });

program
  .command('status')
  .description('Show migration status')
  .action(async () => {
    try {
      await migrationRunner.status();
      await migrationRunner.close();
      process.exit(0);
    } catch (error) {
      console.error('Status check failed:', error);
      process.exit(1);
    }
  });

program
  .command('validate')
  .description('Validate migration files')
  .action(async () => {
    try {
      const result = await migrationValidator.validate();

      if (result.valid) {
        console.log('✓ All migrations are valid');
        process.exit(0);
      } else {
        console.error('✗ Migration validation failed:');
        result.errors.forEach(error => console.error(\`  - \${error}\`));
        process.exit(1);
      }
    } catch (error) {
      console.error('Validation failed:', error);
      process.exit(1);
    }
  });

program.parse();
`;

    return {
      path: path.join(outputDirectory, 'api/src/scripts/migrate.ts'),
      content,
    };
  }
}

export const enhancedMigrationsGenerator = new EnhancedMigrationsGenerator();
