const { Setting } = require("../../models");
const { ValidationError } = require("../../utils/errors");

class adminSettingsService {
  async getSettings() {
    const rows = await Setting.findAll({ order: [["updated_at", "DESC"]] });
    return {
      settings: rows.map(s => ({ key: s.key, value: s.valueJson, updatedAt: s.updated_at })),
    };
  }

  async setSetting(key, data, adminId) {
    if (!key) throw new ValidationError("key is required");
    const valueJson = data?.value;
    if (typeof valueJson === "undefined") throw new ValidationError("value is required");

    const existing = await Setting.findOne({ where: { key } });
    if (!existing) {
      const created = await Setting.create({ key, valueJson, updatedBy: adminId });
      return { setting: created };
    }

    await existing.update({ valueJson, updatedBy: adminId });
    return { setting: existing };
  }
}

module.exports = new adminSettingsService();
