const Brand = require("../models/Brand");
const { checkValidations } = require("../plugins/controllersHelperFunctions")
const { body, validationResult } = require('express-validator')
const { _sr } = require("../plugins/serverResponses")
const maxAttachmentSize = 2048


//@desc Create a brand
//@route POST /api/brands/
//@access Private
const createbrand = [
    [
        body('title').notEmpty().withMessage(_sr.fa.required.title),
        body('description').notEmpty().withMessage(_sr.fa.required.description),
        body('link').notEmpty().trim().isLowercase().withMessage(_sr.fa.required.field),

    ],
    checkValidations(validationResult),
    async (req, res) => {
  const { title, link, description } = req.body;
        const data = {
            title, link, description,
        }

        if (req.files?.logo) {
            const image = req.files.logo
            const fileName = 'brands' + Date.now() + '.' + image.name
            const acceptableFormats = ['png', 'jpg', 'jpeg', 'webp']
            if (!acceptableFormats.includes(image.mimetype.split('/')[1]))
              return res.status(422).json({ validation: { logo: { msg: _faSr.format.image } } })
            if (image.size / 1024 > maxAttachmentSize)
              return res
                .status(422)
                .json({ validation: { logo: { msg: `حجم تصویر نباید بیشتر از ${maxAttachmentSize} KB باشد.` } } })
            data.logo = fileName
            await image.mv(`./static/uploads/images/brands/${fileName}`)
          }else{
            res.status(422).json({ validation: { logo: { msg: `تصویر را ارسال کنید` } } })
          }

      


        const linkAvailable = await Brand.findOne({ link });
        if (linkAvailable) {
            res.status(400).json(_sr.fa.duplicated.link);
        }

        const brand = await Brand.create(data);

        res.status(201).json(brand);

    }

]


//@desc Get to all brands
//@route GET /api/brands/
//@access Public
const getbrands = async (req, res) => {
    const brand = await Brand.find().limit(8);

    res.status(200).json(brand);
};


//@desc Get to brand by id
//@route GET /api/brands/id/:id
//@access Public
const getbrand = async (req, res) => {
    const brand = await Brand.findById(req.params.id);
    if (!brand) {
        res.status(404).json(_sr.fa.not_found.item_id)
    }
    res.status(200).json(brand);
};


//@desc Update a brand
//@route Put /api/brands/:id
//@access Private
const updatebrand = [
    [
        body('title').notEmpty().withMessage(_sr.fa.required.title),
        body('description').notEmpty().withMessage(_sr.fa.required.description),
        body('link').notEmpty().trim().isLowercase().withMessage(_sr.fa.required.field),

    ],
    checkValidations(validationResult),
    async (req, res) => {
        const { title, link, description } = req.body;
        const data = {
            title, link, description,
        }

        if (req.files?.logo) {
            const image = req.files.logo
            const fileName = 'brands' + Date.now() + '.' + image.name
            const acceptableFormats = ['png', 'jpg', 'jpeg', 'webp']
            if (!acceptableFormats.includes(image.mimetype.split('/')[1]))
              return res.status(422).json({ validation: { image: { msg: _faSr.format.image } } })
            if (image.size / 1024 > maxAttachmentSize)
              return res
                .status(422)
                .json({ validation: { image: { msg: `حجم تصویر نباید بیشتر از ${maxAttachmentSize} KB باشد.` } } })
            data.logo = fileName
            await image.mv(`./static/uploads/images/brands/${fileName}`)
          }

        const brand = await Brand.findById(req.params.id);
        if (!brand) {
            res.status(404).json(_sr.fa.not_found.item_id);
        }

        const linkAvailable = await Brand.findOne({ link });
        if (linkAvailable && linkAvailable.id != req.params.id) {
            res.status(400).json(_sr.fa.duplicated.link);
        }

        const updateBrand = await Brand.findByIdAndUpdate(
            req.params.id,
            data,
            { new: true }
        );

        res.status(201).json(updateBrand);

    }
]


//@desc Delete a brand
//@route DELETE /api/brands/:id
//@access Private
const deletebrand = async (req, res) => {
    const brand = await Brand.findById(req.params.id);


    if (!brand) {
        res.status(404).json(_sr.fa.not_found.item_id);
    }

    await brand.deleteOne();

    res.status(201).json(brand);

};


module.exports = {
    createbrand,
    getbrands,
    getbrand,
    updatebrand,
    deletebrand,
};
