import {
    createCategory,
    getAllCategory,
    getCategoryId,
    updateCategory,
    deleteCategory,
} from "../services/categoryService.js";
import Product from '../models/productsModel.js'

import { generateUniqueSlug } from "../utils/slugifyUnique.js";
import { getProductsByCategory } from "../services/productService.js";

/* -------------------- CREATE -------------------- */
export const createCategoryController = async (req, res) => {
    try {
        const { name, description, parentCategory } = req.body;

        if (!name) return res.status(400).json({ message: "Name is required" });
        if (!description)
            return res.status(400).json({ message: "Description is required" });
        if (!req.file)
            return res.status(400).json({ message: "Image is required" });

        const slug = await generateUniqueSlug(name);

        const payload = {
            name,
            slug,
            description,
            parentCategory: parentCategory || null,
        };

        // ✔️ FIXED: pass req.file to service
        const category = await createCategory(payload, req.file);

        return res.status(201).json({
            message: "Category created successfully",
            category,
        });

    } catch (error) {
        return res.status(400).json({ message: error.message });
    }
};



/* -------------------- GET ALL -------------------- */
export const getAllCategoryController = async (req, res) => {
    try {
        const categories = await getAllCategory();

        // Add product count to each category
        const result = await Promise.all(
            categories.map(async(cat) => {
                const count = await Product.countDocuments({ category : cat._id })
                return {
                    ...cat._doc,
                    productCount : count
                }
            })
        )
        res.json({ categories : result })
    } catch (error) {
        res.status(500).json({ message : error.message})
    }
};

/* -------------------- GET BY ID -------------------- */
export const getCategoryByIdController = async (req, res) => {
    try {
        const category = await getCategoryId(req.params.id);
        res.json(category);
    } catch (error) {
        res.status(404).json({ message: error.message });
    }
};

/* -------------------- UPDATE -------------------- */
export const updatedCategoryController = async (req, res) => {
    try {
        const updates = { ...req.body };

        if (updates.name) {
            updates.slug = await generateUniqueSlug(updates.name);
        }

        // ✔️ FIXED: pass req.file to service
        const category = await updateCategory(req.params.id, updates, req.file);

        return res.json({
            message: "Category updated successfully",
            category,
        });

    } catch (error) {
        res.status(400).json({ message: error.message });
    }
};

/* -------------------- DELETE -------------------- */
export const deleteCategoryController = async (req, res) => {
    try {
        const result = await deleteCategory(req.params.id);
        res.json(result);
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
};


export const getProductsByCategoryController = async (rqe,res) => {
    try {
        const products = await getProductsByCategory(req.params.id)

        res.json({
            success : true,
            count : products.length,
            products
        })
    } catch (error) {
        res.status(400).json({ message : error.message })
    }
}