"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createUser = void 0;
const zod_1 = require("zod");
const zod_validation_error_1 = require("zod-validation-error");
const extensions_core_1 = require("@awell-health/extensions-core");
const settings_1 = require("../../../settings");
const config_1 = require("./config");
const client_1 = require("../../client");
const constants_1 = require("../../constants");
const lodash_1 = require("lodash");
exports.createUser = {
    key: 'createUser',
    title: 'Create user',
    description: 'Creates a user using the Chat API.',
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: false,
    onActivityCreated: async (payload, onComplete, onError) => {
        try {
            const { settings: { applicationId, chatApiToken, deskApiToken }, fields: { userId, metadata, issueAccessToken, profileUrl }, } = (0, extensions_core_1.validate)({
                schema: zod_1.z.object({
                    settings: settings_1.SettingsValidationSchema,
                    fields: config_1.FieldsValidationSchema,
                }),
                payload,
            });
            const client = new client_1.SendbirdClient({
                applicationId,
                chatApiToken,
                deskApiToken,
            });
            const res = await client.chatApi.createUser({
                user_id: userId,
                nickname: parseNickname(payload),
                metadata,
                issue_access_token: issueAccessToken,
                profile_url: profileUrl !== null && profileUrl !== void 0 ? profileUrl : constants_1.DEFAULT_PROFILE_URL,
            });
            await onComplete({ data_points: { userId: res.data.user_id } });
        }
        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.message },
                            error: {
                                category: 'WRONG_INPUT',
                                message: error.message,
                            },
                        },
                    ],
                });
            }
            else if ((0, client_1.isSendbirdChatError)(err)) {
                const events = (0, client_1.sendbirdChatErrorToActivityEvent)(err);
                await onError({ events });
            }
            else {
                const message = err.message;
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: message },
                            error: {
                                category: 'SERVER_ERROR',
                                message,
                            },
                        },
                    ],
                });
            }
        }
    },
};
const parseNickname = (payload) => {
    var _a, _b, _c, _d;
    const nickname = payload.fields.nickname;
    if (!(0, lodash_1.isEmpty)(nickname))
        return nickname;
    const firstName = (_b = (_a = payload.patient.profile) === null || _a === void 0 ? void 0 : _a.first_name) !== null && _b !== void 0 ? _b : '';
    const lastName = (_d = (_c = payload.patient.profile) === null || _c === void 0 ? void 0 : _c.last_name) !== null && _d !== void 0 ? _d : '';
    if ((0, lodash_1.isEmpty)(firstName) && (0, lodash_1.isEmpty)(lastName))
        throw new Error('The required nickname has not been specified, and neither the first name nor last name of the patient has been set in their profile');
    return `${firstName} ${lastName}`.trim();
};
//# sourceMappingURL=createUser.js.map