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


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

    if(goodsData.id) {
        try {
            const updatedGood = await Goods.findOne({
                where: goodsData.id
            });

            if(updatedGood) {
                updatedGood.update(goodsData).then(() => {
                    req.body.goodId = goodsData.id;
                    next();
                });
            }else {
                next(new GoodsNotFoundError())
            }


        }catch (e) {
            next(e);
        }
    }else {
        try {
            Goods.create(goodsData).then(createdGoods => {
                req.body.goodId = createdGoods.id;
                next();
            }).catch((e) => {
               next(new InternalServerError());
            });

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