const uuid = require('node-uuid');
import {GoodsAttributes} from "../../models/index";
const multer = require('multer');
import InternalServerError from '../../utils/customErrors/internalServerError';


const storage = multer.diskStorage({
    destination:  (req, file, cb) => {
        cb(null, 'public/photoGoods/')
    },
    filename: (req, file, cb) => {
        const extension = file.originalname.split('.')[file.originalname.split('.').length - 1];
        const uniqueFileName = uuid.v1();

        cb(null, uniqueFileName + '.' + extension);
    }
});
const upload = multer({ storage: storage }).single('file');



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

    upload(req, res, (err) => {
        if (err instanceof multer.MulterError) {
            next(new InternalServerError());
        } else if (err) {
            next(new InternalServerError());
        }

        GoodsAttributes.findOne({
            where: {
                id: idAttribute
            }
        }).then(elem => {
            const newImgArray = elem.imgUrlArray.concat([req.file.filename]);
            req.body.goodId = elem.goodsId;

            elem.update({
                imgUrlArray: newImgArray
            }).then(result => {
               next();
            });

        });

    });

};