"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPatientEnrolledInTrack = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const zod_1 = __importDefault(require("zod"));
const lodash_1 = require("lodash");
exports.isPatientEnrolledInTrack = {
    key: 'isPatientEnrolledInTrack',
    category: extensions_core_1.Category.WORKFLOW,
    title: 'Check patient track enrollment status',
    description: 'Checks whether the patient is enrolled, has been enrolled, or is scheduled to be enrolled in a specific track. This is time-based and will return the status of the track at the time of the check.',
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: false,
    supports_automated_retries: true,
    onEvent: async ({ payload, onComplete, helpers }) => {
        var _a, _b, _c, _d, _e, _f;
        const { fields: { trackDefinitionId }, pathway: { id: pathwayId }, } = (0, extensions_core_1.validate)({
            schema: zod_1.default.object({
                fields: config_1.FieldsValidationSchema,
                pathway: config_1.PathwayValidationSchema,
            }),
            payload,
        });
        const sdk = await helpers.awellSdk();
        // status can be ['active', 'completed', 'stopped', 'discarded']
        const tracksResponse = await sdk.orchestration.query({
            careflowTracks: {
                __args: {
                    careflow_id: pathwayId,
                    statuses: ['active', 'completed'],
                },
                tracks: {
                    definition_id: true,
                    status: true,
                    start_date: true,
                    end_date: true,
                },
            },
            scheduledTracksForPathway: {
                __args: {
                    pathway_id: pathwayId,
                },
                scheduled_tracks: {
                    track_definition_id: true,
                    scheduled_date: true,
                },
            },
        });
        const trackElements = (_c = (_b = (_a = tracksResponse.careflowTracks) === null || _a === void 0 ? void 0 : _a.tracks) === null || _b === void 0 ? void 0 : _b.filter((track) => track.definition_id === trackDefinitionId)) !== null && _c !== void 0 ? _c : [];
        // Find if the patient has been enrolled in the track
        const hasBeenEnrolledInTrack = trackElements.some((track) => track.status === 'completed' &&
            track.end_date !== null &&
            track.end_date !== undefined);
        // Find if the patient is currently enrolled in the track
        const isEnrolledInTrack = trackElements.some((track) => track.status === 'active');
        const scheduledTracks = (_f = (_e = (_d = tracksResponse.scheduledTracksForPathway) === null || _d === void 0 ? void 0 : _d.scheduled_tracks) === null || _e === void 0 ? void 0 : _e.filter((track) => track.track_definition_id === trackDefinitionId)) !== null && _f !== void 0 ? _f : [];
        // Find if the patient is scheduled to be enrolled in the track
        const trackIsScheduled = scheduledTracks.length > 0;
        let trackScheduledDate = null;
        if (scheduledTracks.length > 0) {
            // Find the earliest scheduled_date among queued scheduled tracks.
            const earliestScheduledTrack = scheduledTracks.reduce((earliest, current) => {
                if ((0, lodash_1.isNil)(earliest.scheduled_date))
                    return current;
                if ((0, lodash_1.isNil)(current.scheduled_date))
                    return earliest;
                return new Date(current.scheduled_date) <
                    new Date(earliest.scheduled_date)
                    ? current
                    : earliest;
            });
            trackScheduledDate = earliestScheduledTrack.scheduled_date;
        }
        await onComplete({
            data_points: {
                has_been_enrolled_in_track: hasBeenEnrolledInTrack.toString(),
                is_enrolled_in_track: isEnrolledInTrack.toString(),
                track_is_scheduled: trackIsScheduled.toString(),
                track_scheduled_date: trackScheduledDate,
            },
        });
    },
};
//# sourceMappingURL=isPatientEnrolledInTrack.js.map