import { Client } from 'pg';
import * as fs from 'fs';
import * as path from 'path';
import * as dotenv from 'dotenv';

// Load environment variables
dotenv.config();

const client = new Client({
  host: process.env.DATABASE_HOST || 'localhost',
  port: parseInt(process.env.DATABASE_PORT || '5555'),
  user: process.env.DATABASE_USER || 'maternal_user',
  password: process.env.DATABASE_PASSWORD,
  database: process.env.DATABASE_NAME || 'maternal_app',
});

const MIGRATIONS_DIR = __dirname;

async function runMigrations() {
  try {
    await client.connect();
    console.log('Connected to database');

    // Create migrations tracking table
    await client.query(`
      CREATE TABLE IF NOT EXISTS schema_migrations (
        version VARCHAR(50) PRIMARY KEY,
        executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      );
    `);

    // Get list of migration files
    const files = fs
      .readdirSync(MIGRATIONS_DIR)
      .filter((file) => file.startsWith('V') && file.endsWith('.sql'))
      .sort();

    console.log(`Found ${files.length} migration files`);

    for (const file of files) {
      const version = file.split('_')[0]; // Extract V001, V002, etc.

      // Check if migration already executed
      const result = await client.query(
        'SELECT version FROM schema_migrations WHERE version = $1',
        [version],
      );

      if (result.rows.length > 0) {
        console.log(`✓ Migration ${version} already executed`);
        continue;
      }

      // Read and execute migration
      const migrationPath = path.join(MIGRATIONS_DIR, file);
      const sql = fs.readFileSync(migrationPath, 'utf-8');

      console.log(`Running migration ${version}...`);
      await client.query(sql);

      // Record migration
      await client.query(
        'INSERT INTO schema_migrations (version) VALUES ($1)',
        [version],
      );

      console.log(`✓ Migration ${version} completed`);
    }

    console.log('All migrations completed successfully');
  } catch (error) {
    console.error('Migration error:', error);
    process.exit(1);
  } finally {
    await client.end();
  }
}

runMigrations();
