
import { Client } from 'pg'
import fs from 'fs'
import path from 'path'
import dotenv from 'dotenv'

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

// Parse connection string for PG
// Supabase connection string is usually: postgres://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres
// But we might only have URL and Key in env.
// If we don't have the connection string, we can't run this.
// Let's check .env.local content (securely).
// Actually, I can't see .env.local content due to security rules usually, but I can ask the code to read it.
// If DATABASE_URL is in .env.local, we are good.

async function migrate() {
    if (!process.env.DATABASE_URL) {
        console.error("DATABASE_URL is missing in .env.local. Cannot run migration directly.")
        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)
    } finally {
        await client.end()
    }
}

migrate()
