const Database = require('better-sqlite3');
const path = require('path');
const dbPath = path.join(__dirname, './data/school.db');
const db = new Database(dbPath);

const targetLevel = process.argv[2];
const validLevels = ['primary', 'secondary', 'high_school', 'tertiary'];

if (!targetLevel || !validLevels.includes(targetLevel)) {
  console.log(`Usage: node switch_level.js [${validLevels.join('|')}]`);
  process.exit(1);
}

try {
  db.transaction(() => {
    // 1. Update school_settings
    db.prepare("UPDATE school_settings SET value = ? WHERE key = 'education_level' AND is_deleted = 0")
      .run(targetLevel);
      
    // 2. Set is_default = 1 for the target configuration level, and 0 for others
    db.prepare('UPDATE education_level_configs SET is_default = 0 WHERE is_deleted = 0')
      .run();
    
    db.prepare('UPDATE education_level_configs SET is_default = 1 WHERE level = ? AND is_deleted = 0')
      .run(targetLevel);
  })();

  console.log(`Successfully updated database education level to: "${targetLevel}"`);
  
  // Print updated tables
  const settings = db.prepare("SELECT * FROM school_settings WHERE is_deleted = 0").all();
  const configs = db.prepare('SELECT level, is_default FROM education_level_configs WHERE is_deleted = 0').all();
  console.log('Updated settings:', settings);
  console.log('Updated configs:', configs);
} catch (err) {
  console.error('Failed to update database level:', err.message);
}
