const { Setting } = require('../models');

class SettingsController {
  async getAll(req, res, next) {
    try {
      const group = req.query.group;
      const where = group ? { setting_group: group } : {};
      const settings = await Setting.findAll({ where });
      res.json({ settings });
    } catch (error) {
      next(error);
    }
  }

  async getByKey(req, res, next) {
    try {
      const setting = await Setting.findOne({
        where: { setting_key: req.params.key },
      });
      if (!setting) {
        return res.status(404).json({ error: 'Setting not found' });
      }
      res.json({ setting });
    } catch (error) {
      next(error);
    }
  }

  async getGroups(req, res, next) {
    try {
      const groups = await Setting.aggregate('setting_group', 'DISTINCT', { plain: false });
      res.json({ groups: groups.map((g) => g.DISTINCT).filter(Boolean) });
    } catch (error) {
      next(error);
    }
  }

  async update(req, res, next) {
    try {
      const { setting_value } = req.body;
      const setting = await Setting.findOne({
        where: { setting_key: req.params.key },
      });
      if (!setting) {
        return res.status(404).json({ error: 'Setting not found' });
      }
      setting.setting_value = setting_value;
      await setting.save();
      res.json({ setting });
    } catch (error) {
      next(error);
    }
  }

  async bulkUpdate(req, res, next) {
    try {
      const { settings } = req.body;
      if (!Array.isArray(settings)) {
        return res.status(400).json({ error: 'settings must be an array' });
      }
      const results = [];
      for (const item of settings) {
        const [setting] = await Setting.upsert({
          setting_key: item.setting_key,
          setting_value: item.setting_value,
          setting_group: item.setting_group,
          description: item.description,
        });
        results.push(setting);
      }
      res.json({ settings: results });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new SettingsController();
