const fs = require("fs");
const path = require("path");
const portfolioItemModel = require("../../models/home/portfolioItemModel");

const baseUrl = process.env.BASE_URL || "http://localhost:3000";
const uploadPath = "uploads/home/portfolio";

const PortfolioItemController = {
  // ✅ Create
  create: async (req, res) => {
    try {
      const file = req.file;
      const { media_alt = "", item_heading = "", item_link = "" } = req.body;

      if (!file) {
        return res.status(400).json({ success: false, message: "Media file is required." });
      }

      const media_url = `/${uploadPath}/${file.filename}`;

      const newItem = await portfolioItemModel.create({
        media_url,
        media_alt,
        item_heading,
        item_link,
      });

      res.status(201).json({
        success: true,
        message: "Portfolio item uploaded successfully.",
        data: {
          ...newItem.toJSON(),
          media_url: baseUrl.replace(/\/$/, "") + media_url,
        },
      });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  // ✅ Get All
  getAll: async (req, res) => {
    try {
      const items = await portfolioItemModel.findAll({
        order: [["createdAt", "DESC"]],
      });

      const result = items.map(item => ({
        ...item.toJSON(),
        media_url: baseUrl.replace(/\/$/, "") + item.media_url,
      }));

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

  // ✅ Get Single
  getById: async (req, res) => {
    try {
      const { id } = req.params;
      const item = await portfolioItemModel.findByPk(id);

      if (!item) {
        return res.status(404).json({ success: false, message: "Portfolio item not found." });
      }

      res.status(200).json({
        success: true,
        data: {
          ...item.toJSON(),
          media_url: baseUrl.replace(/\/$/, "") + item.media_url,
        },
      });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  // ✅ Update
  update: async (req, res) => {
    try {
      const { id } = req.params;
      const item = await portfolioItemModel.findByPk(id);

      if (!item) {
        return res.status(404).json({ success: false, message: "Portfolio item not found." });
      }

      let media_url = item.media_url;

      if (req.file) {
        // Delete old file
        const oldFilePath = path.join(__dirname, "../../", item.media_url);
        if (fs.existsSync(oldFilePath)) fs.unlinkSync(oldFilePath);

        media_url = `/${uploadPath}/${req.file.filename}`;
      }

      const { media_alt = item.media_alt, item_heading = item.item_heading, item_link = item.item_link } = req.body;

      await item.update({ media_url, media_alt, item_heading, item_link });

      res.status(200).json({
        success: true,
        message: "Portfolio item updated successfully.",
        data: {
          ...item.toJSON(),
          media_url: baseUrl.replace(/\/$/, "") + media_url,
        },
      });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  // ✅ Delete
  delete: async (req, res) => {
    try {
      const { id } = req.params;
      const item = await portfolioItemModel.findByPk(id);

      if (!item) {
        return res.status(404).json({ success: false, message: "Portfolio item not found." });
      }

      // Delete file from storage
      const filePath = path.join(__dirname, "../../", item.media_url);
      if (fs.existsSync(filePath)) fs.unlinkSync(filePath);

      await item.destroy();

      res.status(200).json({ success: true, message: "Portfolio item deleted successfully." });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },
};

module.exports = PortfolioItemController;
