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

exports.getSettings = async (req, res) => {
  try {
    const settings = await Setting.findAll();
    res.json(settings);
  } catch (error) {
    res.status(500).json({ message: 'Error al obtener configuraciones' });
  }
};

exports.updateSetting = async (req, res) => {
  const { key, value } = req.body;
  try {
    let setting = await Setting.findByPk(key);
    if (setting) {
      setting.value = value;
      await setting.save();
    } else {
      setting = await Setting.create({ key, value });
    }
    res.json(setting);
  } catch (error) {
    res.status(500).json({ message: 'Error al actualizar configuración' });
  }
};

// Seed default settings if not exist
exports.seedSettings = async () => {
  try {
    const defaults = [
      { key: 'referral_bonus', value: '1.00', description: 'Bono por referido ($)' },
      { key: 'min_withdraw', value: '10.00', description: 'Monto mínimo de retiro ($)' }
    ];

    for (const def of defaults) {
      await Setting.findOrCreate({ where: { key: def.key }, defaults: def });
    }
  } catch (error) {
    console.error('Error seeding settings:', error);
  }
};
