"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPatientEnrolledInCareFlow = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const zod_1 = require("zod");
const lodash_1 = require("lodash");
const addEventLog_1 = require("../../../../../src/lib/awell/addEventLog");
const graphql_1 = require("../../gql/graphql");
const isWithinDayRange = (startDateIso, dayRange) => {
    const startDate = new Date(startDateIso);
    const now = new Date();
    // Get difference between now and start date in milliseconds
    const diffTime = now.getTime() - startDate.getTime();
    // Convert to days
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    // Return true if start date is within the day range
    return diffDays <= dayRange;
};
exports.isPatientEnrolledInCareFlow = {
    key: 'isPatientEnrolledInCareFlow',
    category: extensions_core_1.Category.WORKFLOW,
    title: 'Is patient already enrolled in care flow',
    description: 'Checks whether the patient is already enrolled in the current care flow definition.',
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: false, // We don't have patients and pathways in Preview, only cases.
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        const { patient: { id: patientId }, pathway: { id: pathwayId, definition_id: currentPathwayDefinitionId }, fields: { pathwayStatus, careFlowDefinitionIds, dayRange }, } = (0, extensions_core_1.validate)({
            schema: zod_1.z.object({
                patient: config_1.PatientValidationSchema,
                pathway: config_1.PathwayValidationSchema,
                fields: config_1.FieldsValidationSchema,
            }),
            payload,
        });
        const sdk = await helpers.awellSdk();
        const { patientPathways: { patientPathways }, } = await sdk.orchestration.query({
            patientPathways: {
                __args: {
                    patient_id: patientId,
                    filters: {
                        status: {
                            in: pathwayStatus !== null && pathwayStatus !== void 0 ? pathwayStatus : [graphql_1.PathwayStatus.Active]
                        }
                    },
                },
                patientPathways: {
                    id: true,
                    title: true,
                    pathway_definition_id: true,
                    release_id: true,
                    start_date: true,
                    complete_date: true,
                    status: true,
                },
            },
        });
        const getCareFlowsThatMatchFilters = () => patientPathways
            // Exclude the current care flow instance
            .filter((careFlow) => careFlow.id !== pathwayId)
            // Filter by care flow definition ids
            .filter((careFlow) => {
            if ((0, lodash_1.isNil)(careFlowDefinitionIds) || (0, lodash_1.isEmpty)(careFlowDefinitionIds)) {
                return careFlow.pathway_definition_id === currentPathwayDefinitionId;
            }
            return careFlowDefinitionIds.includes(careFlow.pathway_definition_id);
        })
            // Filter by day range
            .filter((careFlow) => {
            if ((0, lodash_1.isNil)(dayRange)) {
                return true;
            }
            return isWithinDayRange(careFlow.start_date, dayRange);
        });
        const careFlows = getCareFlowsThatMatchFilters();
        const nbrOFResults = careFlows.length;
        const isPatientEnrolledInCareFlowResult = nbrOFResults > 0;
        await onComplete({
            data_points: {
                result: String(isPatientEnrolledInCareFlowResult),
                nbrOfResults: String(nbrOFResults),
                careFlowIds: careFlows.map((careFlow) => careFlow.id).join(','),
            },
            events: [
                (0, addEventLog_1.addActivityEventLog)({
                    message: isPatientEnrolledInCareFlowResult
                        ? `Patient was already enrolled in this care flow. Care flow IDs: ${careFlows
                            .map((careFlow) => careFlow.id)
                            .join(',')}`
                        : `Patient was not previously enrolled in this care flow.`,
                }),
            ],
        });
    },
};
//# sourceMappingURL=isPatientEnrolledInCareFlow.js.map