// backend/models/settingModel.js
const db = require('../config/db');

const Setting = {
  /**
   * Retrieves the settings for a specific institution.
   * @param {number} institution_id
   * @returns {Promise<object|undefined>} The settings object.
   */
  findByInstitutionId: async (institution_id) => {
    const [rows] = await db.query('SELECT * FROM settings WHERE institution_id = ?', [institution_id]);
    return rows[0];
  },

  /**
   * Creates or updates the settings for an institution (an "upsert" operation).
   * @param {number} institution_id
   * @param {object} settingsData
   * @param {string|null} settingsData.sms_base_url
   * @param {string|null} settingsData.sms_sender_id
   * @param {string|null} settingsData.sms_api_key
   * @param {string} [settingsData.timezone]
   * @returns {Promise<boolean>} True if the operation was successful.
   */
  createOrUpdate: async (institution_id, { sms_base_url, sms_sender_id, sms_api_key, timezone, logo_url, contact_phone }) => {
    const sql = `
      INSERT INTO settings (institution_id, sms_base_url, sms_sender_id, sms_api_key, timezone, logo_url, contact_phone)
      VALUES (?, ?, ?, ?, ?, ?, ?)
      ON DUPLICATE KEY UPDATE
        sms_base_url = VALUES(sms_base_url),
        sms_sender_id = VALUES(sms_sender_id),
        sms_api_key = VALUES(sms_api_key),
        timezone = VALUES(timezone),
        logo_url = VALUES(logo_url),
        contact_phone = VALUES(contact_phone)
    `;
    const [result] = await db.query(sql, [institution_id, sms_base_url, sms_sender_id, sms_api_key, timezone || 'IST', logo_url, contact_phone]);
    return result.affectedRows > 0;
  }
};

module.exports = Setting;