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

const migrationPath = path.join(__dirname, 'database', 'migrations', '0003_add_time_slots.sql');

console.log('Applying time slots 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, 50) + '...');
                } catch (err) {
                    // Ignore duplicate column errors
                    if (!err.message.includes('duplicate column')) {
                        throw err;
                    } else {
                        console.log('⚠ Column already exists, skipping');
                    }
                }
            }
        }
        
        console.log('\n✓ Time slots migration completed successfully');
        console.log('✓ Added start_time and end_time columns to blocked_dates table');
        console.log('✓ You can now block specific time slots or full days\n');
        
        await database.close();
        process.exit(0);
    } catch (error) {
        console.error('Migration failed:', error.message);
        process.exit(1);
    }
}

applyMigration();
