"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseStringToPhoneNumber = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const extensions_core_2 = 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");
exports.parseStringToPhoneNumber = {
    key: 'parseStringToPhoneNumber',
    title: 'Parse text to phone number',
    description: 'Transform or parse text to a phone number.',
    category: extensions_core_2.Category.DATA,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: true,
    onEvent: async ({ payload, onComplete }) => {
        const { fields: { text, countryCallingCode }, } = (0, extensions_core_2.validate)({
            schema: zod_1.z.object({
                fields: config_1.FieldsValidationSchema,
            }),
            payload,
        });
        const events = [];
        const getPhoneNumber = () => {
            const parsed = extensions_core_1.E164PhoneValidationSchema.safeParse(text);
            /**
             * If E164 validation passes, the phone number is already in E164 format.
             */
            if (parsed.success) {
                events.push((0, addEventLog_1.addActivityEventLog)({
                    message: `Text input is a valid E164 phone number.`,
                }));
                return parsed.data;
            }
            /**
             * If the country calling code is not provided, we can throw a validation error.
             */
            if ((0, lodash_1.isNil)(countryCallingCode)) {
                events.push((0, addEventLog_1.addActivityEventLog)({
                    message: `Text input is not a valid E164 phone number and no country calling code was provided.`,
                }));
                throw new zod_1.ZodError(parsed.error.issues);
            }
            events.push((0, addEventLog_1.addActivityEventLog)({
                message: `Text input is not a valid E164 phone number. Trying again by adding country calling code (${countryCallingCode}).`,
            }));
            /**
             * Try parsing the number with the country calling code prepended this time.
             */
            const withCode = `+${countryCallingCode}${text}`;
            return extensions_core_1.E164PhoneValidationSchema.parse(withCode);
        };
        await onComplete({
            data_points: {
                phoneNumber: getPhoneNumber(),
            },
            events,
        });
    },
};
//# sourceMappingURL=parseStringToPhoneNumber.js.map