const Category = require("../models/categoryModel");
const {
  deleteOldCategoryIcon,
} = require("../storage/middlewareStorage/uploadCategoryMedia");

exports.getAllCategories = async (req, res) => {
  try {
    const categories = await Category.find();
    res.status(200).json({
      status: "success",
      results: categories.length,
      data: { categories },
    });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.getCategory = async (req, res) => {
  try {
    const category = await Category.findById(req.params.id);
    if (!category) {
      return res.status(404).json({ message: "Category not found" });
    }
    res.status(200).json({ status: "success", data: { category } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.createCategory = async (req, res) => {
  try {
    // If file uploaded, set icon field
    if (req.file) req.body.icon = req.file.filename;

    const newCategory = await Category.create(req.body);
    res
      .status(201)
      .json({ status: "success", data: { category: newCategory } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.updateCategory = async (req, res) => {
  try {
    const category = await Category.findById(req.params.id);
    if (!category)
      return res.status(404).json({ message: "Category not found" });

    // Handle Image Update
    if (req.file) {
      await deleteOldCategoryIcon(category.icon); // Delete old
      req.body.icon = req.file.filename; // Set new
    }

    const updatedCategory = await Category.findByIdAndUpdate(
      req.params.id,
      req.body,
      {
        new: true,
        runValidators: true,
      }
    );

    res
      .status(200)
      .json({ status: "success", data: { category: updatedCategory } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.deleteCategory = async (req, res) => {
  try {
    const category = await Category.findById(req.params.id);
    if (!category)
      return res.status(404).json({ message: "Category not found" });

    // Delete image from server
    await deleteOldCategoryIcon(category.icon);

    // Delete from DB
    await Category.findByIdAndDelete(req.params.id);

    res.status(204).json({ status: "success", data: null });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};
