"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResponseError = exports.mapSendgridErrorsToActivityErrors = exports.SendgridClient = void 0;
const mail_1 = __importDefault(require("@sendgrid/mail"));
const client_1 = __importDefault(require("@sendgrid/client"));
const classes_1 = require("@sendgrid/helpers/classes");
Object.defineProperty(exports, "ResponseError", { enumerable: true, get: function () { return classes_1.ResponseError; } });
const lodash_1 = require("lodash");
/**
 * We're using this validateStatus to help produce the expected result.
 * Unforunately, it's not documented well and the suggested action is to use .then() and .catch() instead.
 *
 * Something undocumented in the sendgrid client:
 * The response array [Response, any] in the callback is comprised of the response and the request body.
 * EDIT: ^^ incorrect. Still TBD, but removing validation for now.
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const validateStatus = (validStatus) => (err, response) => {
    var _a;
    if (!(0, lodash_1.isNil)(err)) {
        throw err;
    }
    if (Number(response === null || response === void 0 ? void 0 : response.statusCode) !== Number(validStatus)) {
        throw Error(`Error: status response was ${(_a = response === null || response === void 0 ? void 0 : response.statusCode) !== null && _a !== void 0 ? _a : ''}, was not ${validStatus}`);
    }
};
class SendgridClient {
    constructor({ apiKey }) {
        this.mail = {
            send: async (args) => await this._mailService.send(args),
        };
        this.marketing = {
            contacts: {
                addOrUpdate: async (args) => {
                    return await this._sendgridClient.request({
                        url: '/v3/marketing/contacts',
                        method: 'PUT',
                        body: JSON.stringify({
                            contacts: args.contacts,
                            list_ids: args.listIds,
                        }),
                    });
                },
                importStatus: async (jobId) => {
                    return await this._sendgridClient.request({
                        url: `/v3/marketing/contacts/imports/${jobId}`,
                        method: 'GET',
                    });
                },
            },
        };
        this.groups = {
            suppressions: {
                add: async (groupId, email) => {
                    return await this._sendgridClient.request({
                        url: `/v3/asm/groups/${groupId}/suppressions`,
                        method: 'POST',
                        body: {
                            recipient_emails: [email],
                        },
                    });
                },
                remove: async (groupId, email) => {
                    return await this._sendgridClient.request({
                        url: `/v3/asm/groups/${groupId}/suppressions/${email}`,
                        method: 'DELETE',
                    });
                },
            },
        };
        this._sendgridClient = client_1.default;
        this._sendgridClient.setApiKey(apiKey);
        this._mailService = mail_1.default;
        this._mailService.setClient(this._sendgridClient);
    }
}
exports.SendgridClient = SendgridClient;
const isDetailedError = (error) => {
    return (typeof error.response.body === 'object' &&
        'errors' in error.response.body &&
        Array.isArray(error.response.body.errors));
};
const mapSendgridErrorsToActivityErrors = (error) => {
    const errorTitle = `${error.message} (${error.code})`;
    if (isDetailedError(error)) {
        const errorList = error.response.body.errors;
        return errorList.map((errorItem) => {
            const text = typeof errorItem === 'string'
                ? errorItem
                : `${!(0, lodash_1.isNil)(errorItem.field) ? `${errorItem.field}: ` : ''}${errorItem.message}${!(0, lodash_1.isNil)(errorItem.help) ? `; Help: ${errorItem.help}` : ''}`;
            return {
                date: new Date().toISOString(),
                text: { en: text },
                error: {
                    category: 'SERVER_ERROR',
                    message: text,
                },
            };
        });
    }
    return [
        {
            date: new Date().toISOString(),
            text: { en: errorTitle },
            error: {
                category: 'SERVER_ERROR',
                // eslint-disable-next-line @typescript-eslint/no-base-to-string
                message: `${JSON.stringify(error.response.body)}`,
            },
        },
    ];
};
exports.mapSendgridErrorsToActivityErrors = mapSendgridErrorsToActivityErrors;
//# sourceMappingURL=sendgridClient.js.map