import { Pool } from 'pg';
import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import 'dotenv/config';

const __dirname = dirname(fileURLToPath(import.meta.url));

if (!process.env.DB_URL) throw new Error('DB_URL is required');

const pool = new Pool({
  connectionString: process.env.DB_URL,
  ssl: { rejectUnauthorized: false },
});

const sql = readFileSync(join(__dirname, 'schema.sql'), 'utf-8');

try {
  await pool.query(sql);
  console.log('✅ Schema applied successfully');
} catch (e) {
  console.error('❌ Migration failed:', e);
  process.exit(1);
} finally {
  await pool.end();
}
