const categoryServices = require('../services/category.service');

const { BadRequestError } = require('../core/error.response');
const { OK } = require('../core/success.response');

class categoryController {
    async createCategory(req, res) {
        let { nameCategory, slug, parentId, isActive, level } = req.body;
        if (!nameCategory || !slug) {
            throw new BadRequestError('Bạn đang thiếu thông tin !');
        }

        let image = null;
        if (req.file) {
            const { uploadSingle } = require('../config/cloudinaryUpload');
            image = await uploadSingle(req.file, 'categories');
        }

        if (parentId === '' || parentId === 'null' || parentId === 'undefined') {
            parentId = null;
        }

        const category = await categoryServices.createCategory({
            nameCategory,
            slug,
            parentId,
            isActive,
            image,
            level,
        });
        return new OK({
            message: 'Tạo danh mục thành công !',
            metadata: category,
        }).send(res);
    }

    async updateCategory(req, res) {
        const { id } = req.params;
        let { nameCategory, slug, parentId, isActive, oldImage } = req.body;

        let image = null;
        if (req.file) {
            const { uploadSingle } = require('../config/cloudinaryUpload');
            image = await uploadSingle(req.file, 'categories');
        }

        if (parentId === '' || parentId === 'null' || parentId === 'undefined') {
            parentId = null;
        }

        const category = await categoryServices.updateCategory({
            id,
            nameCategory,
            slug,
            parentId,
            isActive,
            image,
            oldImage,
            level: req.body.level,
        });

        return new OK({
            message: 'Cập nhật danh mục thành công !',
            metadata: category,
        }).send(res);
    }

    async deleteCategory(req, res) {
        const { id } = req.params;
        await categoryServices.deleteCategory(id);
        return new OK({
            message: 'Xóa danh mục thành công !',
            metadata: true,
        }).send(res);
    }

    async getAllCategory(req, res) {
        const category = await categoryServices.getAllCategory();
        return new OK({
            message: 'Lấy danh mục thành công !',
            metadata: category,
        }).send(res);
    }
}

module.exports = new categoryController();
