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

async function applyMigration() {
  const db = new Database();
  
  try {
    console.log('📝 Applying blocked dates migration...');
    
    // Create blocked_dates table
    await db.run(`
      CREATE TABLE IF NOT EXISTS blocked_dates (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        blocked_date DATE NOT NULL UNIQUE,
        reason TEXT,
        created_by INTEGER,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (created_by) REFERENCES users(id)
      )
    `);
    console.log('✅ Created blocked_dates table');
    
    // Create index
    await db.run(`
      CREATE INDEX IF NOT EXISTS idx_blocked_dates_date ON blocked_dates(blocked_date)
    `);
    console.log('✅ Created index on blocked_dates');
    
    // Create booking_config table
    await db.run(`
      CREATE TABLE IF NOT EXISTS booking_config (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        config_key TEXT UNIQUE NOT NULL,
        config_value TEXT NOT NULL,
        description TEXT,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `);
    console.log('✅ Created booking_config table');
    
    // Insert default config
    await db.run(`
      INSERT OR IGNORE INTO booking_config (config_key, config_value, description) VALUES
      ('min_advance_hours', '24', 'Minimum hours in advance required for bookings (default: 24 hours)')
    `);
    
    await db.run(`
      INSERT OR IGNORE INTO booking_config (config_key, config_value, description) VALUES
      ('allow_same_day_booking', '0', 'Allow same-day bookings (0 = No, 1 = Yes)')
    `);
    console.log('✅ Inserted default booking configuration');
    
    // Verify tables
    const blockedDatesTable = await db.get(`
      SELECT name FROM sqlite_master WHERE type='table' AND name='blocked_dates'
    `);
    
    const bookingConfigTable = await db.get(`
      SELECT name FROM sqlite_master WHERE type='table' AND name='booking_config'
    `);
    
    console.log('\n✅ Migration completed successfully!');
    console.log('  - blocked_dates table:', blockedDatesTable ? 'EXISTS' : 'NOT FOUND');
    console.log('  - booking_config table:', bookingConfigTable ? 'EXISTS' : 'NOT FOUND');
    
    db.close();
  } catch (error) {
    console.error('❌ Migration error:', error);
    db.close();
    process.exit(1);
  }
}

applyMigration();
