/**
 * Vacation Settings Model
 *
 * vacation_settings 테이블 CRUD + startup migration
 */

const { getPool } = require('./userModel');

async function getAll() {
  const db = getPool();
  const [rows] = await db.query('SELECT * FROM vacation_settings ORDER BY id ASC');
  return rows;
}

async function getByKey(key) {
  const db = getPool();
  const [rows] = await db.query('SELECT * FROM vacation_settings WHERE setting_key = ?', [key]);
  return rows[0] || null;
}

async function updateSettings(settings, updatedBy) {
  const db = getPool();
  for (const { setting_key, setting_value } of settings) {
    await db.query(
      'UPDATE vacation_settings SET setting_value = ?, updated_by = ? WHERE setting_key = ?',
      [setting_value, updatedBy, setting_key]
    );
  }
  return getAll();
}

async function loadAsObject() {
  const rows = await getAll();
  const obj = {};
  for (const row of rows) {
    obj[row.setting_key] = row.setting_value;
  }
  return obj;
}

async function runMigration() {
  const db = getPool();
  const fs = require('fs');
  const path = require('path');
  const sqlFile = path.join(__dirname, '..', '..', 'migrations', '20260323_sprint001_vacation_overhaul.sql');
  const sql = fs.readFileSync(sqlFile, 'utf8');
  const statements = sql.split(';').map(s => s.trim()).filter(s => s.length > 0);
  for (const stmt of statements) {
    try {
      await db.query(stmt);
    } catch (err) {
      if (['ER_DUP_FIELDNAME', 'ER_TABLE_EXISTS_ERROR', 'ER_DUP_KEYNAME'].includes(err.code)) {
        // Already migrated — safe to ignore
      } else {
        throw err;
      }
    }
  }
  console.log('[tkuser] Sprint 001 migration completed');
}

async function runGenericMigration(filename) {
  const db = getPool();
  const fs = require('fs');
  const path = require('path');
  const sqlFile = path.join(__dirname, '..', '..', 'migrations', filename);
  const sql = fs.readFileSync(sqlFile, 'utf8');
  const statements = sql.split(';').map(s => s.trim()).filter(s => s.length > 0);
  for (const stmt of statements) {
    try {
      await db.query(stmt);
    } catch (err) {
      if (['ER_DUP_FIELDNAME', 'ER_TABLE_EXISTS_ERROR', 'ER_DUP_KEYNAME'].includes(err.code)) {
        // Already migrated — safe to ignore
      } else {
        throw err;
      }
    }
  }
  console.log(`[tkuser] Migration ${filename} completed`);
}

module.exports = { getAll, getByKey, updateSettings, loadAsObject, runMigration, runGenericMigration };
