const { section5Video } = require("../../models/home/section5VideoModel");
const uploadDir = "uploads/home/videos";

const Section5VideoController = {
  create: async (req, res) => {
    try {
      const { video_alt } = req.body;
      const data = { video_alt };

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

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

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

  getAll: async (req, res) => {
    try {
      const result = await section5Video.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 section5Video.getSingle(req.params.id);
      if (!result) return res.status(404).json({ success: false, message: "Video 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 { video_alt } = req.body;
      const data = { video_alt };

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

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

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

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

module.exports = Section5VideoController;
