/**
 * Database Migration Runner
 * Uses drizzle-kit to apply schema migrations
 */

import { drizzle } from 'drizzle-orm/postgres-js';
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import postgres from 'postgres';
import { logger } from '../utils/logger';

/**
 * Run all pending migrations
 * @param connectionString PostgreSQL connection string
 */
export async function runMigrations(connectionString: string): Promise<void> {
  logger.info('Starting database migrations...');

  const migrationClient = postgres(connectionString, { max: 1 });
  const db = drizzle(migrationClient);

  try {
    await migrate(db, { migrationsFolder: './drizzle' });
    logger.info('✓ Database migrations completed successfully');
  } catch (error) {
    logger.error({ error }, 'Migration failed');
    throw error;
  } finally {
    await migrationClient.end();
  }
}

/**
 * CLI entry point for running migrations
 */
if (require.main === module) {
  const connectionString = process.env.DATABASE_URL;
  
  if (!connectionString) {
    console.error('ERROR: DATABASE_URL environment variable is required');
    process.exit(1);
  }

  runMigrations(connectionString)
    .then(() => {
      console.log('Migrations complete');
      process.exit(0);
    })
    .catch((error) => {
      console.error('Migration failed:', error);
      process.exit(1);
    });
}
