const database = require('./server/config/database');
const fs = require('fs');
const path = require('path');

const migrationPath = path.join(__dirname, 'database', 'migrations', '0004_return_journey_details.sql');

console.log('Applying return journey details migration...');

async function applyMigration() {
    try {
        // Initialize database connection
        await database.initialize();
        
        const migration = fs.readFileSync(migrationPath, 'utf8');
        const statements = migration.split(';').filter(stmt => stmt.trim());
        
        for (const statement of statements) {
            if (statement.trim()) {
                try {
                    await database.run(statement);
                    console.log('✓ Executed:', statement.trim().substring(0, 60) + '...');
                } catch (err) {
                    // Ignore duplicate column errors
                    if (!err.message.includes('duplicate column')) {
                        throw err;
                    } else {
                        console.log('⚠ Column already exists, skipping');
                    }
                }
            }
        }
        
        console.log('\n✓ Return journey details migration completed successfully');
        console.log('✓ Added return journey columns to bookings table');
        console.log('✓ System can now store complete return journey information\n');
        
        await database.close();
        process.exit(0);
    } catch (error) {
        console.error('Migration failed:', error.message);
        process.exit(1);
    }
}

applyMigration();
