"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 graphql_1 = require("../../gql/graphql");
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,
    onEvent: async ({ payload, onComplete, helpers }) => {
        var _a, _b, _c;
        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();
        const elementsResponse = await sdk.orchestration.query({
            pathwayElements: {
                __args: {
                    pathway_id: pathwayId,
                },
                elements: {
                    definition_id: true,
                    type: true,
                    status: true,
                    start_date: true,
                    end_date: true,
                },
            },
        });
        // Filter for track elements that match the specified definition ID
        const trackElements = (_c = (_b = (_a = elementsResponse.pathwayElements) === null || _a === void 0 ? void 0 : _a.elements) === null || _b === void 0 ? void 0 : _b.filter((element) => element.type === graphql_1.ElementType.Track &&
            element.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 === graphql_1.ElementStatus.Done &&
            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 === graphql_1.ElementStatus.Active);
        // Find if the patient is scheduled to be enrolled in the track
        const trackIsScheduled = trackElements.some((track) => track.status === graphql_1.ElementStatus.Scheduled);
        // Find the earliest scheduled date among scheduled tracks
        const scheduledTracks = trackElements.filter((track) => track.status === graphql_1.ElementStatus.Scheduled);
        let trackScheduledDate = null;
        if (scheduledTracks.length > 0) {
            // Find the earliest start_date among scheduled tracks
            const earliestScheduledTrack = scheduledTracks.reduce((earliest, current) => {
                if ((0, lodash_1.isNil)(earliest.start_date))
                    return current;
                if ((0, lodash_1.isNil)(current.start_date))
                    return earliest;
                return new Date(current.start_date) < new Date(earliest.start_date)
                    ? current
                    : earliest;
            });
            trackScheduledDate = earliestScheduledTrack.start_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