// backend/controllers/settingsController.js

const Setting = require('../models/settingModel');

/**
 * @desc    Get the settings for the user's institution
 * @route   GET /api/settings
 * @access  Private (Admin)
 */
exports.getSettings = async (req, res) => {
  try {
    const { institution_id } = req.user;
    let settings = await Setting.findByInstitutionId(institution_id);

    // If no settings exist yet, return a default object for the frontend
    if (!settings) {
      settings = {
        institution_id,
        sms_base_url: '',
        sms_sender_id: '',
        sms_api_key: '',
        timezone: 'UTC',
      };
    }
    res.status(200).json(settings);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching settings.', error: error.message });
  }
};

/**
 * @desc    Update the settings for the user's institution
 * @route   PUT /api/settings
 * @access  Private (Admin)
 */
exports.updateSettings = async (req, res) => {
  try {
    const { institution_id } = req.user;
    
    // Whitelist the fields that can be updated
    const { sms_base_url, sms_sender_id, sms_api_key, timezone } = req.body;
    
    const settingsData = { sms_base_url, sms_sender_id, sms_api_key, timezone };

    const success = await Setting.createOrUpdate(institution_id, settingsData);
    
    if (success) {
      res.status(200).json({ message: 'Settings updated successfully.' });
    } else {
      // This case is unlikely with upsert but included for completeness
      res.status(400).json({ message: 'Failed to update settings. No changes were detected.' });
    }
  } catch (error) {
    res.status(500).json({ message: 'Error updating settings.', error: error.message });
  }
};