const pool = require('../db');

async function run() {
    console.log('Starting notifications table migration...');
    try {
        await pool.query(`
            CREATE TABLE IF NOT EXISTS notifications (
                id SERIAL PRIMARY KEY,
                user_id INTEGER REFERENCES users(id),
                username TEXT NOT NULL,
                type TEXT NOT NULL DEFAULT 'issue_resolved',
                title TEXT NOT NULL,
                message TEXT NOT NULL,
                issue_number INTEGER,
                read BOOLEAN DEFAULT FALSE,
                created_at TIMESTAMP DEFAULT NOW()
            )
        `);
        console.log('✓ notifications table created (or already exists)');

        await pool.query(`
            CREATE INDEX IF NOT EXISTS idx_notifications_username
            ON notifications(username)
        `);
        console.log('✓ username index created');

        await pool.query(`
            CREATE INDEX IF NOT EXISTS idx_notifications_read
            ON notifications(username, read)
        `);
        console.log('✓ username/read index created');

        console.log('Migration complete.');
    } catch (err) {
        console.error('Migration failed:', err.message);
        throw err;
    }
}

module.exports = { run };

// Self-execute when run directly
if (require.main === module) {
    run().then(() => process.exit(0)).catch(() => process.exit(1));
}
