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

/**
 * Migration script to add missing mobile-related columns to the users table.
 */
const migrate = async () => {
    console.log('🚀 Starting User Table Mobile Columns Migration...');

    try {
        // 1. Add ios_onboarding_sent
        console.log('Checking ios_onboarding_sent...');
        try {
            await db.query(`
                ALTER TABLE users 
                ADD COLUMN ios_onboarding_sent TINYINT(1) DEFAULT 0
            `, [], { silent: true });
            console.log('✅ Added ios_onboarding_sent column.');
        } catch (err) {
            if (err.message.includes('Duplicate column name')) {
                console.log('ℹ️ ios_onboarding_sent already exists.');
            } else {
                throw err;
            }
        }

        // 2. Add mobile_reminder_sent
        console.log('Checking mobile_reminder_sent...');
        try {
            await db.query(`
                ALTER TABLE users 
                ADD COLUMN mobile_reminder_sent TINYINT(1) DEFAULT 0
            `, [], { silent: true });
            console.log('✅ Added mobile_reminder_sent column.');
        } catch (err) {
            if (err.message.includes('Duplicate column name')) {
                console.log('ℹ️ mobile_reminder_sent already exists.');
            } else {
                throw err;
            }
        }

        // 3. Add subscription_source
        console.log('Checking subscription_source...');
        try {
            await db.query(`
                ALTER TABLE users 
                ADD COLUMN subscription_source VARCHAR(50) DEFAULT NULL
            `, [], { silent: true });
            console.log('✅ Added subscription_source column.');
        } catch (err) {
            if (err.message.includes('Duplicate column name')) {
                console.log('ℹ️ subscription_source already exists.');
            } else {
                throw err;
            }
        }

        console.log('🥇 Migration completed successfully.');
        process.exit(0);

    } catch (error) {
        console.error('❌ Migration FAILED:', error.message);
        process.exit(1);
    }
};

migrate();
