const { sliderBanner } = require("../../models/home/sliderBannerModel");
const uploadDir = "uploads/slider_banner_images";

const SliderBannerController = {
  create: async (req, res) => {
    try {
      const { main_heading, content, button_text, button_link, img_alt } = req.body;

      const data = {
        main_heading: main_heading?.trim(),
        content,
        button_text,
        button_link,
        img_alt,
      };

      if (req.file) {
        data.banner_img = `/${uploadDir}/${req.file.filename}`;
      }

      const result = await sliderBanner.create(data);
      if (result?.error) {
        return res.status(400).json({ success: false, message: result.error });
      }

      res.status(201).json({
        success: true,
        message: "Slider banner created successfully!",
        data: result,
      });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  getAll: async (req, res) => {
    try {
      const result = await sliderBanner.getAll();
      if (!result.length) {
        return res.status(404).json({ success: false, message: "No slider banners found." });
      }
      res.status(200).json({ success: true, data: result });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  getSingle: async (req, res) => {
    try {
      const entry = await sliderBanner.getSingle(req.params.id);
      if (!entry) {
        return res.status(404).json({ success: false, message: "Slider banner not found." });
      }
      res.status(200).json({ success: true, data: entry });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  update: async (req, res) => {
    try {
      const { main_heading, content, button_text, button_link, img_alt } = req.body;

      const data = {
        main_heading: main_heading?.trim(),
        content,
        button_text,
        button_link,
        img_alt,
      };

      if (req.file) {
        data.banner_img = `/${uploadDir}/${req.file.filename}`;
      }

      const updated = await sliderBanner.update(req.params.id, data);
      if (!updated) {
        return res.status(404).json({ success: false, message: "Slider banner not found." });
      }

      res.status(200).json({ success: true, message: "Slider banner updated successfully!", data: updated });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  delete: async (req, res) => {
    try {
      const deleted = await sliderBanner.delete(req.params.id);
      if (!deleted) {
        return res.status(404).json({ success: false, message: "Slider banner not found." });
      }
      res.status(200).json({ success: true, ...deleted });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },
};

module.exports = SliderBannerController;
