const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// Load env vars manually
const envPath = path.resolve(__dirname, '../.env');
const envContent = fs.readFileSync(envPath, 'utf8');
const envVars = {};
envContent.split('\n').forEach(line => {
    const [key, value] = line.split('=');
    if (key && value) {
        envVars[key.trim()] = value.trim().replace(/"/g, '');
    }
});

const dbConfig = {
    host: envVars.DB_HOST || 'localhost',
    user: envVars.DB_USER || 'nordic_app_user',
    password: envVars.DB_PASSWORD,
    database: envVars.DB_NAME || 'nordic_storium',
    port: parseInt(envVars.DB_PORT || '3306')
};

async function main() {
    let connection;
    try {
        console.log('Connecting to database...');
        connection = await mysql.createConnection(dbConfig);
        console.log('Connected!');

        // Add image_url column to categories table if it doesn't exist
        console.log('Adding image_url column to categories table...');
        try {
            await connection.query('ALTER TABLE categories ADD COLUMN image_url VARCHAR(500)');
            console.log('Added image_url column to categories');
        } catch (e) {
            if (e.code !== 'ER_DUP_FIELDNAME') throw e;
            console.log('image_url column already exists in categories');
        }

        console.log('✅ Migration completed successfully!');

    } catch (error) {
        console.error('❌ Error:', error);
    } finally {
        if (connection) await connection.end();
    }
}

main();
