import Category from "../models/categoryModel.js";
import fs from "fs";
import path from "path";

/* -------------------- CREATE -------------------- */
export const createCategory = async (data, file) => {
    if (!file) throw new Error("Image is required");

    const imagePath = `/uploads/category/${file.filename}`;

    const category = new Category({
        ...data,
        image: imagePath,
    });

    await category.save();
    return category;
};

/* -------------------- GET ALL -------------------- */
export const getAllCategory = async () => {
    return await Category.find().populate("parentCategory");
};

/* -------------------- GET BY ID -------------------- */
export const getCategoryId = async (id) => {
    const category = await Category.findById(id);
    if (!category) throw new Error("Category not found");
    return category;
};

/* -------------------- UPDATE -------------------- */
export const updateCategory = async (id, updates, file) => {
    const category = await Category.findById(id);
    if (!category) throw new Error("Category not found");

    // if new image uploaded → delete old image & save new
    if (file) {
        const oldImagePath = path.join(process.cwd(), category.image);
        if (fs.existsSync(oldImagePath)) {
            fs.unlinkSync(oldImagePath);
        }

        updates.image = `/uploads/category/${file.filename}`;
    }

    Object.assign(category, updates);
    await category.save();

    return category;
};

/* -------------------- DELETE -------------------- */
export const deleteCategory = async (id) => {
    const category = await Category.findById(id);
    if (!category) throw new Error("Category not found");

    if (category.image) {
        const filePath = path.join(process.cwd(), category.image);
        if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
    }

    await Category.findByIdAndDelete(id);

    return { message: "Category deleted successfully" };
};
