"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, onError, helpers }) => {
        helpers.log({ fields: payload.fields }, 'Processing parseStringToPhoneNumber');
        try {
            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.`,
                    }));
                    helpers.log({ text, countryCallingCode, phoneNumber: parsed.data }, 'Parsed text to 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.`,
                    }));
                    const err = new zod_1.ZodError(parsed.error.issues);
                    helpers.log({ text, countryCallingCode, err }, 'error', err);
                    throw err;
                }
                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}`;
                let phoneNumber;
                try {
                    phoneNumber = extensions_core_1.E164PhoneValidationSchema.parse(withCode);
                }
                catch (err) {
                    helpers.log({ err }, 'error', err);
                    throw err;
                }
                helpers.log({ text, countryCallingCode, phoneNumber }, 'Parsed text to phone number');
                return phoneNumber;
            };
            await onComplete({
                data_points: {
                    phoneNumber: getPhoneNumber(),
                },
                events,
            });
        }
        catch (err) {
            helpers.log({ err }, 'error', err);
            const error = err;
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: { en: error.message },
                        error: {
                            category: 'BAD_REQUEST',
                            message: error.message,
                        },
                    },
                ],
            });
        }
    },
};
//# sourceMappingURL=parseStringToPhoneNumber.js.map