import { LoadType } from '../../../types/UserReports.js';
import localsHelper from '../../../utils/localsHelper.js';
import { ReportQuery } from '../../../types/ReportQuery.js';
import logger from '../../../utils/logger.js';
import { getActiveJourneyValue } from '../../../utils/sessionHelper.js';

const streamDownloadAsyncData = async (args) => {
    const { token, services, tableId, reportId, id, queryParams, res } = args;
    const query = {
        ...queryParams,
    };
    return services.reportingService.downloadAsyncReport(token, reportId, id, tableId, query, res);
};
const streamDownloadSyncData = async (args) => {
    const { token, services, queryParams, definition, res } = args;
    const { variant } = definition;
    const { resourceName, specification } = variant;
    if (!specification) {
        logger.error(`No specification found for definition ID: ${definition.id} variant ID: ${variant.id}`);
        throw new Error(`No specification found for definition ID: ${definition.id} variant ID: ${variant.id}`);
    }
    const reportQuery = new ReportQuery({
        fields: specification.fields,
        template: specification.template,
        queryParams: {
            ...queryParams,
        },
        definitionsPath: queryParams.dataProductDefinitionsPath,
    });
    return services.reportingService.downloadSyncReport(token, resourceName, reportQuery, res);
};
const downloadReport = async ({ req, services, res, redirect, loadType, }) => {
    const { dprUser, token } = localsHelper.getValues(res);
    const { reportId, id, tableId, dataProductDefinitionsPath, cols: columns, sortedAsc, sortColumn } = req.body;
    const { downloadPermissionService } = services;
    const canDownloadReport = await downloadPermissionService.downloadEnabledForReport(dprUser.id, reportId, id);
    if (!canDownloadReport) {
        res.redirect(redirect);
    }
    else {
        const streamDownloadQueryParams = {
            dataProductDefinitionsPath,
            ...(columns && { columns: JSON.parse(columns) }),
            ...(sortedAsc && { sortedAsc }),
            ...(sortColumn && { sortColumn }),
        };
        const definition = await services.reportingService.getDefinition(token, reportId, id, dataProductDefinitionsPath);
        logger.info(`Initiating streaming...`);
        if (loadType === LoadType.SYNC) {
            await streamDownloadSyncData({
                definition,
                services,
                token,
                queryParams: streamDownloadQueryParams,
                res,
            });
        }
        else {
            await streamDownloadAsyncData({
                services,
                token,
                reportId,
                id,
                tableId,
                queryParams: streamDownloadQueryParams,
                res,
            });
        }
    }
};
const setUpDownload = (res, req, definitionData, columns, loadType, requestData) => {
    const { downloadingEnabled } = localsHelper.getValues(res);
    let downloadConfig;
    if (downloadingEnabled) {
        const { definitionsPath, csrfToken } = localsHelper.getValues(res);
        const { downloadActionEndpoint } = localsHelper.getRouteLocals(res);
        const { tableId, id, reportId } = req.params;
        const downloadEnabled = getActiveJourneyValue(req, { id, reportId }, 'downloadEnabled');
        const { reportName, name, specification } = definitionData;
        const sections = specification.sections || [];
        const downloadColumns = [...new Set([...columns.value, ...sections])];
        const sortColumn = requestData?.queryData?.['sortColumn'];
        const sortedAsc = requestData?.queryData?.['sortedAsc'];
        return {
            enabled: downloadingEnabled,
            name,
            reportName,
            reportId,
            id,
            tableId,
            columns: downloadColumns,
            definitionPath: definitionsPath,
            loadType,
            formAction: downloadActionEndpoint,
            canDownload: downloadEnabled,
            ...(sortColumn && { sortColumn }),
            ...(sortedAsc && { sortedAsc }),
            csrfToken,
        };
    }
    return downloadConfig;
};
var DownloadUtils = {
    downloadReport,
    setUpDownload,
};

export { DownloadUtils as default, downloadReport, setUpDownload };
//# sourceMappingURL=utils.js.map
