import localsHelper from '../../../../utils/localsHelper.js';
import { buildMyReportListRow } from '../../../../components/my-reports/my-reports-list-item/utils.js';
import { ListType } from '../../../../components/my-reports/types.js';
import { evaluateAndUpdateReportStatus } from '../../../../utils/ReportStatus/getReportStatus.js';
import logger from '../../../../utils/logger.js';
import { safeRedirect } from '../../../../utils/http/safeRedirect.js';

class RequestedReportsController {
    services;
    constructor(services) {
        this.services = services;
    }
    /**
     * Gets an individual My Reports row and renders it as a string
     *
     * @param {*} req
     * @param {*} res
     * @return {*}
     */
    GET = async (req, res) => {
        try {
            const { executionId } = req.params;
            const { token, dprUser } = localsHelper.getValues(res);
            // 1. Fetch the stored report
            const requestedReport = await this.services.requestedReportService.getReportByExecutionId(executionId, dprUser.id);
            if (!requestedReport) {
                return res.sendStatus(404);
            }
            // 2. Evaluate + update status using the shared utility
            const { resolution, updated } = await evaluateAndUpdateReportStatus({
                stored: requestedReport,
                services: this.services,
                token,
                res,
            });
            // 3. No change – keep polling
            if (resolution.type === 'NO_CHANGE') {
                return res.sendStatus(204);
            }
            if (!updated) {
                return res.sendStatus(204);
            }
            // 4. Status changed – re-render the row
            const viewModel = buildMyReportListRow(updated, resolution.newStatus, req, res, ListType.REQUESTED);
            return res.render('dpr/components/my-reports/my-reports-list-item/row.njk', { item: viewModel }, (err, html) => {
                if (err) {
                    return res.sendStatus(500);
                }
                return res.type('text/html').send(html);
            });
        }
        catch (error) {
            logger.error(error);
            return res.sendStatus(500);
        }
    };
    /**
     * Remove requested report action
     *
     * @param {*} req
     * @param {*} res
     * @return {*}
     */
    POST = async (req, res) => {
        const { dprUser } = localsHelper.getValues(res);
        const { executionId } = req.params;
        const { returnTo } = req.body;
        const returnToWithTab = `${returnTo}#requested-reports-tab`;
        await this.services.requestedReportService.removeReport(executionId, dprUser.id);
        return safeRedirect(req, res, returnToWithTab);
    };
}

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