const knex = require('knex');
const path = require('path');

// Load environment variables
require('dotenv').config({ path: path.join(__dirname, '../.env') });

async function runMigrations() {
  const knexConfig = {
    client: 'pg',
    connection: {
      host: process.env.DATABASE_HOST,
      port: parseInt(process.env.DATABASE_PORT || '5432', 10),
      database: process.env.DATABASE_NAME,
      user: process.env.DATABASE_USER,
      password: process.env.DATABASE_PASSWORD,
    },
    migrations: {
      directory: path.join(__dirname, '../src/database/migrations'),
      tableName: 'knex_migrations',
      loadExtensions: ['.ts'],
    },
  };

  const db = knex(knexConfig);

  try {
    console.log('🔄 Running database migrations...');
    await db.migrate.latest();
    console.log('✅ Migrations completed successfully!');

    console.log('🌱 Running database seeds...');
    await db.seed.run({
      directory: path.join(__dirname, '../src/database/seeds'),
      loadExtensions: ['.ts'],
    });
    console.log('✅ Seeds completed successfully!');
  } catch (error) {
    console.error('❌ Migration failed:', error);
    process.exit(1);
  } finally {
    await db.destroy();
  }
}

runMigrations();
