const path = require("path");
const { services_detail_media, services_detail_mediaModel } = require("../../models/services_detail_media/services_detail_mediaModel");

const uploadDir = "uploads/services_detail_media";

const ServicesDetailMediaController = {
  create: async (req, res) => {
    try {
      const data = {};

      if (req.file) {
        data.file_url = `${uploadDir}/${req.file.filename}`;
      } else {
        return res.status(400).json({ success: false, message: "File is required." });
      }

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

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

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

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

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

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

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

module.exports = ServicesDetailMediaController;
