const path = require('path');
const { Pool } = require('pg');
const { drizzle } = require('drizzle-orm/node-postgres');
const { migrate } = require('drizzle-orm/node-postgres/migrator');

const migrationsFolder = path.join(__dirname, '..', 'drizzle');

const DATABASE_URL = process.env.DATABASE_URL;
if (!DATABASE_URL) {
  console.error('❌ DATABASE_URL environment variable is not set');
  process.exit(1);
}

const pool = new Pool({ connectionString: DATABASE_URL, max: 2 });
const db = drizzle(pool);

migrate(db, { migrationsFolder })
  .then(() => {
    console.log('✅ Database migrations completed');
    return pool.end();
  })
  .catch((error) => {
    console.error('❌ Migration failed:', error);
    pool.end().finally(() => process.exit(1));
  });
