const { iconBox } = require("../../models/iconboxes/iconBoxModel");
const uploadDir = "uploads/icon_boxes";

const IconBoxController = {
  create: async (req, res) => {
    try {
      const { card_title, card_content, img_alt } = req.body;

      const data = {
        card_title: card_title?.trim(),
        card_content,
        img_alt,
      };

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

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

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

  getAll: async (req, res) => {
    try {
      const result = await iconBox.getAll();
      if (!result.length) {
        return res.status(404).json({ success: false, message: "No icon boxes 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 iconBox.getSingle(req.params.id);
      if (!entry) {
        return res.status(404).json({ success: false, message: "Icon box 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 { card_title, card_content, img_alt } = req.body;

      const data = {
        card_title: card_title?.trim(),
        card_content,
        img_alt,
      };

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

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

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

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

module.exports = IconBoxController;