const { whoWeAre } = require("../../models/home/whoWeAreModel");
const uploadDir = "uploads/who_we_are_images";

const WhoWeAreController = {
  create: async (req, res) => {
    try {
      const {
        span_heading,
        main_heading_1,
        main_heading_2,
        content,
        button_text,
        button_link,
      } = req.body;

      const data = {
        span_heading,
        main_heading_1,
        main_heading_2,
        content,
        button_text,
        button_link,
      };

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

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

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

  getAll: async (req, res) => {
    try {
      const result = await whoWeAre.getAll();
      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 result = await whoWeAre.getSingle(req.params.id);
      if (!result) return res.status(404).json({ success: false, message: "Not found" });
      res.status(200).json({ success: true, data: result });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

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

      const data = {
        span_heading,
        main_heading_1,
        main_heading_2,
        content,
        button_text,
        button_link,
      };

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

      const result = await whoWeAre.update(req.params.id, data);
      if (!result) return res.status(404).json({ success: false, message: "Not found" });

      res.status(200).json({ success: true, message: "Updated successfully", data: result });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

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

module.exports = WhoWeAreController;
