
const { Client } = require('pg');
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');

dotenv.config({ path: '.env.local' });

async function migrate() {
    if (!process.env.DATABASE_URL) {
        console.error("DATABASE_URL is missing in .env.local. Cannot run migration directly.");
        // Fallback: Check if we have standard supabase credentials and try to construct it?
        // Postgres URL: postgres://postgres:[PASSWORD]@[HOST]:[PORT]/postgres
        // We usually don't have the password plain text in env if it's Supabase (unless user added it).
        // If we fail here, we notify/ask user.
        process.exit(1);
    }

    const client = new Client({
        connectionString: process.env.DATABASE_URL,
        ssl: { rejectUnauthorized: false }
    });

    try {
        await client.connect();
        const sqlPath = path.join(process.cwd(), 'migrations', 'new_features.sql');
        const sql = fs.readFileSync(sqlPath, 'utf8');

        await client.query(sql);
        console.log("Migration executed successfully.");
    } catch (err) {
        console.error("Migration failed:", err);
        process.exit(1);
    } finally {
        await client.end();
    }
}

migrate();
