/**
 * System settings model
 * This module handles database operations for system settings
 */

/**
 * Get all system settings
 * @param {Object} db - Database connection pool
 * @param {Function} query - Query function
 * @returns {Promise<Array>} - Array of settings
 */
const getAllSettings = async (db, query) => {
    try {
      const result = await query(
        'SELECT * FROM system_settings ORDER BY category, key'
      );
      return result.rows;
    } catch (error) {
      console.error('Error retrieving system settings:', error);
      throw error;
    }
  };
  
  /**
   * Get settings by category
   * @param {Object} db - Database connection pool
   * @param {Function} query - Query function
   * @param {string} category - Settings category
   * @returns {Promise<Array>} - Array of settings in the category
   */
  const getSettingsByCategory = async (db, query, category) => {
    try {
      const result = await query(
        'SELECT * FROM system_settings WHERE category = $1 ORDER BY key',
        [category]
      );
      return result.rows;
    } catch (error) {
      console.error(`Error retrieving ${category} settings:`, error);
      throw error;
    }
  };
  
  /**
   * Get a specific setting
   * @param {Object} db - Database connection pool
   * @param {Function} query - Query function
   * @param {string} key - Setting key
   * @returns {Promise<Object>} - Setting value
   */
  const getSetting = async (db, query, key) => {
    try {
      const result = await query(
        'SELECT * FROM system_settings WHERE key = $1',
        [key]
      );
      return result.rows[0];
    } catch (error) {
      console.error(`Error retrieving setting ${key}:`, error);
      throw error;
    }
  };
  
  /**
   * Update a setting
   * @param {Object} db - Database connection pool
   * @param {Function} query - Query function
   * @param {string} key - Setting key
   * @param {string} value - Setting value
   * @param {string} category - Setting category
   * @returns {Promise<Object>} - Updated setting
   */
  const updateSetting = async (db, query, key, value, category) => {
    try {
      // Check if setting exists
      const existing = await query(
        'SELECT * FROM system_settings WHERE key = $1',
        [key]
      );
      
      if (existing.rows.length === 0) {
        // Create new setting
        const result = await query(
          'INSERT INTO system_settings (key, value, category) VALUES ($1, $2, $3) RETURNING *',
          [key, value, category]
        );
        return result.rows[0];
      } else {
        // Update existing setting
        const result = await query(
          'UPDATE system_settings SET value = $1, updated_at = NOW() WHERE key = $2 RETURNING *',
          [value, key]
        );
        return result.rows[0];
      }
    } catch (error) {
      console.error(`Error updating setting ${key}:`, error);
      throw error;
    }
  };
  
  /**
   * Update multiple settings at once
   * @param {Object} db - Database connection pool
   * @param {Function} query - Query function
   * @param {Array} settings - Array of settings objects {key, value, category}
   * @returns {Promise<Array>} - Array of updated settings
   */
  const updateSettings = async (db, query, settings) => {
    const client = await db.connect();
    try {
      await client.query('BEGIN');
      
      const updatedSettings = [];
      
      for (const setting of settings) {
        const { key, value, category } = setting;
        
        // Check if setting exists
        const existing = await client.query(
          'SELECT * FROM system_settings WHERE key = $1',
          [key]
        );
        
        let result;
        if (existing.rows.length === 0) {
          // Create new setting
          result = await client.query(
            'INSERT INTO system_settings (key, value, category) VALUES ($1, $2, $3) RETURNING *',
            [key, value, category]
          );
        } else {
          // Update existing setting
          result = await client.query(
            'UPDATE system_settings SET value = $1, updated_at = NOW() WHERE key = $2 RETURNING *',
            [value, key]
          );
        }
        
        updatedSettings.push(result.rows[0]);
      }
      
      await client.query('COMMIT');
      return updatedSettings;
    } catch (error) {
      await client.query('ROLLBACK');
      console.error('Error updating settings:', error);
      throw error;
    } finally {
      client.release();
    }
  };
  
  /**
   * Delete a setting
   * @param {Object} db - Database connection pool
   * @param {Function} query - Query function
   * @param {string} key - Setting key
   * @returns {Promise<boolean>} - Success status
   */
  const deleteSetting = async (db, query, key) => {
    try {
      await query(
        'DELETE FROM system_settings WHERE key = $1',
        [key]
      );
      return true;
    } catch (error) {
      console.error(`Error deleting setting ${key}:`, error);
      throw error;
    }
  };
  
  module.exports = {
    getAllSettings,
    getSettingsByCategory,
    getSetting,
    updateSetting,
    updateSettings,
    deleteSetting
  };