const db = require('../config/database');

class SiteSetting {
  static async getAll(group = null) {
    let query = `
      SELECT s.*
      FROM site_settings s
      INNER JOIN (
        SELECT setting_key, MAX(id) AS max_id
        FROM site_settings
        GROUP BY setting_key
      ) latest
        ON latest.setting_key = s.setting_key
       AND latest.max_id = s.id
    `;
    const params = [];

    if (group) {
      query += ' WHERE setting_group = ?';
      params.push(group);
    }

    query += ' ORDER BY setting_group, setting_key';

    const [rows] = await db.query(query, params);
    return rows;
  }

  static async getByKey(key) {
    const [rows] = await db.query('SELECT * FROM site_settings WHERE setting_key = ?', [key]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async getAllAsObject() {
    const [rows] = await db.query(`
      SELECT s.setting_key, s.setting_value
      FROM site_settings s
      INNER JOIN (
        SELECT setting_key, MAX(id) AS max_id
        FROM site_settings
        GROUP BY setting_key
      ) latest
        ON latest.setting_key = s.setting_key
       AND latest.max_id = s.id
    `);
    const settings = {};
    rows.forEach(row => {
      settings[row.setting_key] = row.setting_value;
    });
    return settings;
  }

  static async update(key, value) {
    const [updateResult] = await db.query(
      'UPDATE site_settings SET setting_value = ?, updated_at = CURRENT_TIMESTAMP WHERE setting_key = ?',
      [value, key]
    );

    if (updateResult.affectedRows > 0) {
      return true;
    }

    const [insertResult] = await db.query(
      'INSERT INTO site_settings (setting_key, setting_value) VALUES (?, ?)',
      [key, value]
    );

    return insertResult.affectedRows > 0;
  }

  static async updateMultiple(settings) {
    const promises = Object.entries(settings).map(([key, value]) =>
      this.update(key, value)
    );
    await Promise.all(promises);
    return true;
  }
}

module.exports = SiteSetting;
