import { captureException } from '@sentry/node';
import AsyncPollingUtils from './utils.js';
import { ErrorHandler } from '../../../../utils/ErrorHandler/ErrorHandler.js';
import { evaluateAndUpdateReportStatus } from '../../../../utils/ReportStatus/getReportStatus.js';
import { getValues } from '../../../../utils/localsHelper.js';

class RequestStatusController {
    layoutPath;
    services;
    constructor(layoutPath, services) {
        this.layoutPath = layoutPath;
        this.services = services;
    }
    // Render status page
    GET = async (req, res, next) => {
        try {
            const pollingRenderData = await AsyncPollingUtils.renderPolling({
                req,
                res,
                services: this.services,
                next,
            });
            res.render(`dpr/routes/journeys/request-report/status/view`, {
                layoutPath: this.layoutPath,
                ...pollingRenderData,
            });
        }
        catch (error) {
            req.body ??= {};
            req.body.title = 'Failed to retrieve report status';
            req.body.errorDescription = 'We were unable to retrieve the report status:';
            req.body.error = new ErrorHandler(error).formatError();
            next(error);
        }
    };
    // Poll request status
    POST = async (req, res, _next) => {
        try {
            const { token, dprUser } = getValues(res);
            const { executionId, currentStatus } = req.body;
            const requestedReport = await this.services.requestedReportService.getReportByExecutionId(executionId, dprUser.id);
            if (!requestedReport) {
                return res.sendStatus(404);
            }
            const { resolution } = await evaluateAndUpdateReportStatus({
                stored: requestedReport,
                services: this.services,
                res,
                token,
            });
            let status = currentStatus;
            if (resolution.type === 'UPDATE') {
                status = resolution.newStatus;
            }
            return res.send({ status });
        }
        catch (error) {
            captureException(error);
            return res.send({ status: 'FAILED' });
        }
    };
}

export { RequestStatusController, RequestStatusController as default };
//# sourceMappingURL=controller.js.map
