import {GoodsAttributes, Goods} from "../../models/index";
import InternalServerError from '../../utils/customErrors/internalServerError';


module.exports = async (req, res, next) => {
    const {goodsAttributesData, goodsId, goodsAttributeId} = req.body.decryptedData;

    req.body.goodId = goodsId;


    if(goodsAttributeId) {
        try {
            const selectedAttribute = await GoodsAttributes.findOne({
                where: {
                    id: goodsAttributeId
                }
            });
            const oldVolumeValue = selectedAttribute.valueAttribute;

            selectedAttribute.update(goodsAttributesData).then(() => {
                Goods.findOne({
                    where: {
                        id: goodsId
                    }
                }).then(selectedGoods => {
                    const {volumesArray} = selectedGoods;

                    volumesArray.splice(
                        volumesArray.indexOf(oldVolumeValue),
                        1,
                        goodsAttributesData.valueAttribute
                    );

                    selectedGoods.update({
                        volumesArray: volumesArray
                    }).then(() => next());

                });
            });

        }catch (e) {
            next(new InternalServerError());
        }

    }else {
        Object.assign(goodsAttributesData, {
            imgUrlArray: [],
            goodsId: goodsId
        });

        try {
            GoodsAttributes.create(goodsAttributesData).then(elem => {
                Goods.findOne({
                    where: {
                        id: goodsId
                    }
                }).then(selectedGoods => {
                    const {volumesArray} = selectedGoods;

                    volumesArray.push(goodsAttributesData.valueAttribute);
                    volumesArray.sort((a, b) => a > b);

                    selectedGoods.update({
                       volumesArray: volumesArray
                    }).then(() => next());

                });
            });
        }catch (e) {
            next(new InternalServerError());
        }

    }
};