"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendFax = void 0;
const zod_1 = require("zod");
const lodash_1 = require("lodash");
const extensions_core_1 = require("@awell-health/extensions-core");
const settings_1 = require("../../settings");
const config_1 = require("./config");
const dataPoints_1 = require("./config/dataPoints");
const fields_1 = require("./config/fields");
const getFaceSheet_1 = require("./facesheets/getFaceSheet");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
exports.sendFax = {
    key: 'sendFax',
    category: extensions_core_1.Category.COMMUNICATION,
    title: 'Send fax',
    description: 'Send fax with WestFax.',
    fields: config_1.fields,
    dataPoints: dataPoints_1.dataPoints,
    previewable: false,
    onActivityCreated: async (payload, onComplete, onError) => {
        const { fields, settings } = (0, extensions_core_1.validate)({
            schema: zod_1.z.object({
                settings: settings_1.SettingsValidationSchema,
                fields: fields_1.FieldsValidationSchema,
            }),
            payload,
        });
        const { productId, feedbackEmail, number, content, addFaceSheet } = fields;
        const { username, password, faceSheetUrl: defaultFaceSheet } = settings;
        try {
            const contentBlob = new Blob([content], { type: 'text/html' });
            const contentFileIndex = addFaceSheet === true ? 1 : 0;
            const formData = new FormData();
            formData.append('Username', username);
            formData.append('Password', password);
            formData.append('Cookies', 'false');
            formData.append('ProductId', productId);
            if (!(0, lodash_1.isNil)(feedbackEmail)) {
                formData.append('FeedbackEmail', feedbackEmail);
            }
            formData.append('Numbers1', number);
            if (addFaceSheet === true) {
                const faceSheetPdfBuffer = await (0, getFaceSheet_1.getFaceSheet)(defaultFaceSheet);
                const faceSheetPdfBlob = new Blob([faceSheetPdfBuffer], {
                    type: 'application/pdf',
                });
                formData.append('Files0', faceSheetPdfBlob, `facesheet.pdf`);
            }
            formData.append(`Files${contentFileIndex}`, contentBlob, 'content.html');
            const requestOptions = {
                method: 'POST',
                body: formData,
                headers: {
                    // zlib cant decompress this requests so we need to set enconding as none
                    'accept-encoding': '',
                },
            };
            const response = await fetch('https://api2.westfax.com/REST/Fax_SendFax/json', requestOptions);
            const jsonResponse = await response.json();
            if (!(0, lodash_1.isNil)(jsonResponse.Success) && jsonResponse.Success === true) {
                const faxId = jsonResponse.Result;
                await onComplete({
                    data_points: {
                        faxId,
                    },
                    events: [
                        (0, addEventLog_1.addActivityEventLog)({
                            message: `WestFax accepted the Fax, the ID of the fax is ${String(faxId)}`,
                        }),
                    ],
                });
            }
            else {
                if (!(0, lodash_1.isNil)(jsonResponse.Success) && jsonResponse.Success === false) {
                    await onError({
                        events: [
                            {
                                date: new Date().toISOString(),
                                text: {
                                    en: 'There is a miss configuration in the WestFax settings',
                                },
                                error: {
                                    category: 'MISSING_FIELDS',
                                    message: jsonResponse.InfoString,
                                },
                            },
                        ],
                    });
                }
                else {
                    await onError({
                        events: [
                            {
                                date: new Date().toISOString(),
                                text: {
                                    en: 'There is a miss configuration in the WestFax settings',
                                },
                                error: {
                                    category: 'MISSING_SETTINGS',
                                    message: 'Missing username or password',
                                },
                            },
                        ],
                    });
                }
            }
        }
        catch (err) {
            const error = err;
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: { en: 'WestFax API reported an error' },
                        error: {
                            category: 'SERVER_ERROR',
                            message: error.message,
                        },
                    },
                ],
            });
        }
    },
};
//# sourceMappingURL=sendFax.js.map