const logger = require('../../log');
const {asyncMiddleware} = require('../utils/middleware');
const {getIn} = require('../utils/functionalHelpers');

module.exports = ({licenceService, conditionsService, prisonerService}) => router => {

    router.get('/review/:sectionName/:bookingId', asyncMiddleware(async (req, res) => {
        const {sectionName, bookingId} = req.params;
        const {licenceStatus} = res.locals;
        logger.debug(`GET /review/${sectionName}/${bookingId}`);

        const licence = getIn(res.locals.licence, ['licence']) || {};
        const stage = getIn(res.locals.licence, ['stage']) || {};
        const licenceVersion = getIn(res.locals.licence, ['version']) || {};

        const showErrors = stagesForRole[req.user.role].includes(stage);
        const errorObject = showErrors ? getErrors(licenceStatus, licence, licence, stage, licenceStatus) : {};

        const data = await conditionsService.populateLicenceWithConditions(licence, errorObject);

        const prisonerInfo = await prisonerService.getPrisonerDetails(bookingId, res.locals.token);

        res.render(`review/${sectionName}`, {
            bookingId,
            data,
            prisonerInfo,
            stage,
            licenceVersion,
            errorObject,
            showErrors,
            postApproval: ['DECIDED', 'MODIFIED', 'MODIFIED_APPROVAL'].includes(stage)
        });
    }));

    function getErrors(licenceStatus, licenceWithAddress, licence, stage, {decisions}) {
        return licenceService.validateFormGroup({licence, stage, decisions});
    }

    return router;
};

const stagesForRole = {
    CA: ['ELIGIBILITY', 'PROCESSING_CA', 'FINAL_CHECKS'],
    RO: ['PROCESSING_RO'],
    DM: ['APPROVAL']
};

@@ -715,67 +715,165 @@
 nst 
-showErrors = stagesForRole%5Breq.user.role%5D.includes(stage
+postApproval = %5B'DECIDED', 'MODIFIED', 'MODIFIED_APPROVAL'%5D.includes(stage);%0A        const showErrors = shouldValidate(req.user.role, stage, postApproval
 );%0A
+%0A
     
@@ -1418,70 +1418,8 @@
 oval
-: %5B'DECIDED', 'MODIFIED', 'MODIFIED_APPROVAL'%5D.includes(stage)
 %0A   
@@ -1521,16 +1521,23 @@
 ecisions
+, tasks
 %7D) %7B%0A   
@@ -1607,16 +1607,23 @@
 ecisions
+, tasks
 %7D);%0A    
@@ -1648,16 +1648,151 @@
 er;%0A%7D;%0A%0A
+function shouldValidate(role, stage, postApproval) %7B%0A    return postApproval ? role === 'CA' : stagesForRole%5Brole%5D.includes(stage);%0A%7D%0A%0A
 const st

Validate review in postApproval only for CA