import {Orders} from "../../models";
const uuid = require('node-uuid');

module.exports = async (req, res, next) => {
    const {orderGoodsData, userData, decryptedData, encryptedData} = req.body;
    const packageId = uuid.v1();

    if(orderGoodsData) {

        orderGoodsData.map(elem => {
            const orderData = Object.assign(userData, elem, {
                packageId: packageId,
                userId: req.body.id || null
            });
            Orders.create(orderData);
        });
        next();
    }else if(decryptedData && encryptedData) {

        let simpleOrder = await Orders.findOne({
            where: {
                packageId: decryptedData.packId
            }
        });

        if(simpleOrder) {
            simpleOrder = Object.assign(simpleOrder.dataValues, {
                packageId: decryptedData.packId,
                goodsId: decryptedData.goodId
            });
            delete simpleOrder.id;
            Orders.create(simpleOrder).then(elem => {
                next();
            }).catch(e => next(e));
        }

    }
};