"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendEmail = void 0;
const config_1 = require("./config");
const extensions_core_1 = require("@awell-health/extensions-core");
const settings_1 = require("../../../settings");
const fields_1 = require("./config/fields");
const zod_validation_error_1 = require("zod-validation-error");
const zod_1 = require("zod");
const client_1 = require("../../../client");
const lodash_1 = require("lodash");
exports.sendEmail = {
    key: 'sendEmail',
    title: 'Send email',
    description: 'Send an email.',
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    previewable: false,
    onActivityCreated: async (payload, onComplete, onError) => {
        var _a, _b;
        try {
            const { patient: { id: patientId }, activity: { id: activityId }, } = payload;
            const { fields: { to, subject, body, fromName, fromEmail }, settings: { apiKey, fromName: defaultFromName, fromEmail: defaultFromEmail, }, } = (0, extensions_core_1.validate)({
                schema: zod_1.z
                    .object({
                    fields: fields_1.FieldsValidationSchema,
                    settings: settings_1.SettingsValidationSchema,
                })
                    .superRefine((value, ctx) => {
                    // if both `fromName` values missing - throw error
                    if ((0, lodash_1.isNil)(value.settings.fromName) &&
                        (0, lodash_1.isNil)(value.fields.fromName)) {
                        ctx.addIssue({
                            code: zod_1.z.ZodIssueCode.custom,
                            fatal: true,
                            message: '"fromName" is missing in both settings and in the action field.',
                        });
                    }
                    // if both `fromEmail` values missing - throw error
                    if ((0, lodash_1.isNil)(value.settings.fromEmail) &&
                        (0, lodash_1.isNil)(value.fields.fromEmail)) {
                        ctx.addIssue({
                            code: zod_1.z.ZodIssueCode.custom,
                            fatal: true,
                            message: '"fromEmail" is missing in both settings and in the action field.',
                        });
                    }
                }),
                payload,
            });
            const sendgridClient = new client_1.SendgridClient({ apiKey });
            await sendgridClient.mail.send({
                from: {
                    /**
                     * '' default needs to be provided for TypeScript
                     * in reality it will throw validation error above if it's not provided
                     * */
                    email: (_a = fromEmail !== null && fromEmail !== void 0 ? fromEmail : defaultFromEmail) !== null && _a !== void 0 ? _a : '',
                    name: (_b = fromName !== null && fromName !== void 0 ? fromName : defaultFromName) !== null && _b !== void 0 ? _b : '',
                },
                to,
                subject,
                html: body,
                // metadata
                customArgs: {
                    website: 'https://awell.health',
                    awellPatientId: patientId,
                    awellActivityId: activityId,
                },
            });
            await onComplete();
        }
        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;
            }
            else if (err instanceof client_1.ResponseError) {
                const events = (0, client_1.mapSendgridErrorsToActivityErrors)(err);
                await onError({
                    events,
                });
                return;
            }
            const error = err;
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: { en: 'Something went wrong while orchestration the action' },
                        error: {
                            category: 'SERVER_ERROR',
                            message: error.message,
                        },
                    },
                ],
            });
        }
    },
};
//# sourceMappingURL=sendEmail.js.map