import {adminPrivateKey} from "../../utils/constans/signUp";
import ForbiddenError from '../../utils/customErrors/forbiddenError';
const CryptoJS = require("crypto-js");
import {roles} from "../../utils/constans/signUp";

module.exports = (req, res, next) => {

    if(req.body.role == roles.ADMIN) {
        if(req.body.encryptedData) {
            try {
                const bytes = CryptoJS.AES.decrypt(req.body.encryptedData.toString(), adminPrivateKey);
                const decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
                req.body.decryptedData = decryptedData;
                next();
            }catch (e) {
                next(new ForbiddenError());
            }
        }else {
            try {
                const bytes  = CryptoJS.AES.decrypt(req.headers.encrypted.toString(), adminPrivateKey);
                const decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
                req.body.decryptedData = decryptedData;
                next();
            }catch (e) {
                next(new ForbiddenError());
            }
        }
    }else {
        next(new ForbiddenError());
    }
};