"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.importStatus = 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 classes_1 = require("@sendgrid/helpers/classes");
const client_1 = require("../../../client");
const types_1 = require("../../../client/types");
const lodash_1 = require("lodash");
// import { isResponseError } from '../../../client/types'
const dataPoints = {
    importStatus: {
        key: 'importStatus',
        valueType: 'string',
    },
    finishedAt: {
        key: 'finishedAt',
        valueType: 'date',
    },
    startedAt: {
        key: 'startedAt',
        valueType: 'date',
    },
    jobType: {
        key: 'jobType',
        valueType: 'string',
    },
    id: {
        key: 'id',
        valueType: 'string',
    },
};
exports.importStatus = {
    key: 'importStatus',
    title: 'Status of Import',
    description: 'Get the status of an Import job',
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    dataPoints,
    previewable: true,
    onActivityCreated: async (payload, onComplete, onError) => {
        try {
            const { fields: { jobId, wait_for_finished }, settings: { apiKey }, } = (0, extensions_core_1.validate)({
                schema: zod_1.z.object({
                    fields: fields_1.FieldsValidationSchema,
                    settings: settings_1.SettingsValidationSchema,
                }),
                payload,
            });
            const sendgridClient = new client_1.SendgridClient({ apiKey });
            let resp;
            if (!(0, lodash_1.isNil)(wait_for_finished)) {
                resp = (await sendgridClient.marketing.contacts.importStatus(jobId))[0]
                    .body;
                for (let i = 0; i < 9; i++) {
                    if ([types_1.ImportStatus.COMPLETED, types_1.ImportStatus.FAILED].includes(resp.status)) {
                        break;
                    }
                    await new Promise((resolve) => setTimeout(resolve, (1000 * 2) ^ i)); // exponential backoff
                    resp = (await sendgridClient.marketing.contacts.importStatus(jobId))[0].body;
                }
            }
            else {
                resp = (await sendgridClient.marketing.contacts.importStatus(jobId))[0]
                    .body;
            }
            await onComplete({
                data_points: {
                    importStatus: resp.status,
                    finishedAt: resp.finished_at,
                    startedAt: resp.started_at,
                    jobType: resp.job_type,
                    id: resp.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.name },
                            error: {
                                category: 'WRONG_INPUT',
                                message: `${error.message}`,
                            },
                        },
                    ],
                });
                return;
            }
            else if (err instanceof classes_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=importStatus.js.map