const settingsModel = require("../models/settingModel");
const SettingsModel = new settingsModel();
const settingsHelper = require("../helpers/settingsHelper");
const settingsService = require("../services/settingsService");
const SettingsHelper = new settingsHelper();
const Response = require("../helpers/responseHelper");
const CacheService = require("../services/CacheService");

class SettingsController {
  async getSettings(req, res) {
    const { setting, category } = req.params;
    try {
      const cacheKey = `settings:${setting}:${category || 'all'}`;
      const result = await CacheService.getOrSet(cacheKey, async () => {
        return SettingsModel.getSettings(setting, category);
      }, 300);
      if (!result || result.length === 0) {
        return Response.error(res, "NOT_FOUND", "No settings found", 404);
      }
      return Response.success(res, result);
    } catch (err) {
      return Response.error(res, "SERVER_ERROR", "No settings found", 500);
    }
  }

  async index(req, res) {
    var { type, flash } = req.params;
    if (!flash) {
      flash = "";
    }
    var discount = await SettingsHelper.webDiscount();
    if (discount === undefined) {
      discount = 0;
    }
    await res.render("settings/settings.ejs", {
      discount: discount,
      flash: flash,
    });
  }

    async setWebDiscount(req,res){
        const {web_discount} = req.body;
        try{
            const result = await SettingsModel.setWebDiscount(web_discount);
            if(result.affectedRows === 0){
                return res.status(404).json({Error: "No settings found"});
            }
            // Invalidate settings cache on update
            CacheService.deleteByPrefix('settings:');
            return res.status(200).json(result);
        }catch(err){
            return res.status(500).json("No settings found");
        }
    }

    async check(req, res){
        try{
            const result = await CacheService.getOrSet('consolidated_settings', async () => {
                return SettingsHelper.consolidatedSettings();
            }, 300);
      return Response.success(res, result);
    } catch (err) {
      return Response.error(res, "SERVER_ERROR", "No settings found", 500);
    }
  }

  async addSetting(req, res) {
    const { setting, category, description, display, value } = req.body;
    try {
      if (!setting || !display) {
        return Response.error(res, "VALIDATION_ERROR", "Setting name and display are required", 400);
      }
      const result = await SettingsModel.addSetting({ setting, category, description, display, value });
      CacheService.deleteByPrefix('settings:');
      CacheService.deleteByPrefix('consolidated_settings');
      return Response.success(res, { id: result, message: "Setting added successfully" });
    } catch (err) {
      return Response.error(res, "SERVER_ERROR", "Failed to add setting", 500);
    }
  }

  async editSetting(req, res) {
    const { id } = req.params;
    const { setting, category, description, display, value } = req.body;
    try {
      if (!id) {
        return Response.error(res, "VALIDATION_ERROR", "Setting ID is required", 400);
      }
      const result = await SettingsModel.updateSetting(id, { setting, category, description, display, value });
      if (result.affectedRows === 0) {
        return Response.error(res, "NOT_FOUND", "Setting not found", 404);
      }
      CacheService.deleteByPrefix('settings:');
      CacheService.deleteByPrefix('consolidated_settings');
      return Response.success(res, { message: "Setting updated successfully" });
    } catch (err) {
      return Response.error(res, "SERVER_ERROR", "Failed to update setting", 500);
    }
  }

  async deleteSetting(req, res) {
    const { id } = req.params;
    try {
      if (!id) {
        return Response.error(res, "VALIDATION_ERROR", "Setting ID is required", 400);
      }
      const result = await SettingsModel.deleteSetting(id);
      if (result.affectedRows === 0) {
        return Response.error(res, "NOT_FOUND", "Setting not found", 404);
      }
      CacheService.deleteByPrefix('settings:');
      CacheService.deleteByPrefix('consolidated_settings');
      return Response.success(res, { message: "Setting deleted successfully" });
    } catch (err) {
      return Response.error(res, "SERVER_ERROR", "Failed to delete setting", 500);
    }
  }
}
module.exports = SettingsController;
