"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assignToCohort = void 0;
const crypto_1 = require("crypto");
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const fields_1 = require("./config/fields");
const zod_validation_error_1 = require("zod-validation-error");
const zod_1 = require("zod");
exports.assignToCohort = {
    key: 'assignToCohort',
    title: 'Assign to cohort',
    description: 'Deterministically assign a value to a cohort number. Given the same input and number of cohorts, the result will always be the same.',
    category: extensions_core_1.Category.MATH,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: true,
    onActivityCreated: async (payload, onComplete, onError) => {
        try {
            const { fields: { input, numberOfCohorts }, } = (0, extensions_core_1.validate)({
                schema: zod_1.z.object({ fields: fields_1.FieldsValidationSchema }),
                payload,
            });
            const hash = (0, crypto_1.createHash)('sha256').update(input).digest('hex');
            const hashInt = parseInt(hash.substring(0, 8), 16);
            const cohortNumber = (hashInt % numberOfCohorts) + 1;
            await onComplete({
                data_points: {
                    cohortNumber: String(cohortNumber),
                },
            });
        }
        catch (err) {
            if (err instanceof zod_1.ZodError) {
                const error = (0, zod_validation_error_1.fromZodError)(err);
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: error.name },
                            error: {
                                category: 'WRONG_INPUT',
                                message: `${error.message}`,
                            },
                        },
                    ],
                });
                return;
            }
            const error = err;
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: { en: 'Something went wrong while orchestrating the action' },
                        error: {
                            category: 'SERVER_ERROR',
                            message: error.message,
                        },
                    },
                ],
            });
        }
    },
};
//# sourceMappingURL=assignToCohort.js.map