"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeReqUFG = void 0;
const req_1 = require("@applitools/req");
const utils = __importStar(require("@applitools/utils"));
function makeReqUFG({ settings, logger }) {
    var _a;
    return (0, req_1.makeReq)({
        baseUrl: settings.ufgServerUrl,
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'X-Auth-Token': settings.accessToken,
            'User-Agent': settings.agentId,
        },
        proxy: settings.proxy,
        useDnsCache: settings.useDnsCache,
        connectionTimeout: (_a = settings.connectionTimeout) !== null && _a !== void 0 ? _a : 300000 /* 5min */,
        requestTimeout: 30000,
        retry: {
            limit: 5,
            timeout: 200,
            statuses: [404, 500, 502, 503, 504],
            codes: ['ECONNRESET', 'ECONNABORTED', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN', 'STUCK_REQUEST'],
        },
        hooks: [handleLogs({ logger }), handleUnexpectedResponse()],
    });
}
exports.makeReqUFG = makeReqUFG;
function handleLogs({ logger: defaultLogger } = {}) {
    const guid = utils.general.guid();
    let counter = 0;
    return {
        beforeRequest({ request, options }) {
            var _a;
            const logger = (_a = options === null || options === void 0 ? void 0 : options.logger) !== null && _a !== void 0 ? _a : defaultLogger;
            let requestId = request.headers.get('x-applitools-eyes-client-request-id');
            if (!requestId) {
                requestId = `${counter++}--${guid}`;
                request.headers.set('x-applitools-eyes-client-request-id', requestId);
            }
            logger === null || logger === void 0 ? void 0 : logger.log(`Request "${options === null || options === void 0 ? void 0 : options.name}" [${requestId}] will be sent to the address "[${request.method}]${request.url}" with body`, options === null || options === void 0 ? void 0 : options.body);
        },
        beforeRetry({ request, attempt, error, response, options }) {
            var _a;
            const logger = (_a = options === null || options === void 0 ? void 0 : options.logger) !== null && _a !== void 0 ? _a : defaultLogger;
            const requestId = request.headers.get('x-applitools-eyes-client-request-id');
            logger === null || logger === void 0 ? void 0 : logger.log(`Request "${options === null || options === void 0 ? void 0 : options.name}" [${requestId}] that was sent to the address "[${request.method}]${request.url}" with body`, options === null || options === void 0 ? void 0 : options.body, `is going to retried due to ${error ? 'an error' : 'a response with status'}`, error !== null && error !== void 0 ? error : `${response.statusText}(${response.status})`);
            request.headers.set('x-applitools-eyes-client-request-id', `${requestId.split('#', 1)[0]}#${attempt + 1}`);
        },
        async afterResponse({ request, response, options }) {
            var _a;
            const logger = (_a = options === null || options === void 0 ? void 0 : options.logger) !== null && _a !== void 0 ? _a : defaultLogger;
            const requestId = request.headers.get('x-applitools-eyes-client-request-id');
            logger === null || logger === void 0 ? void 0 : logger.log(`Request "${options === null || options === void 0 ? void 0 : options.name}" [${requestId}] that was sent to the address "[${request.method}]${request.url}" respond with ${response.statusText}(${response.status})`, !response.ok ? `and body ${JSON.stringify(await response.clone().text())}` : '');
        },
        afterError({ request, error, options }) {
            var _a;
            const logger = (_a = options === null || options === void 0 ? void 0 : options.logger) !== null && _a !== void 0 ? _a : defaultLogger;
            const requestId = request.headers.get('x-applitools-eyes-client-request-id');
            logger === null || logger === void 0 ? void 0 : logger.error(`Request "${options === null || options === void 0 ? void 0 : options.name}" [${requestId}] that was sent to the address "[${request.method}]${request.url}" failed with error`, error);
        },
    };
}
function handleUnexpectedResponse() {
    return {
        async afterResponse({ request, response, options }) {
            if ((options === null || options === void 0 ? void 0 : options.expected) &&
                (utils.types.isArray(options.expected)
                    ? !options.expected.includes(response.status)
                    : options.expected !== response.status)) {
                throw new Error(`Request "${options === null || options === void 0 ? void 0 : options.name}" that was sent to the address "[${request.method}]${request.url}" failed due to unexpected status ${response.statusText}(${response.status}) with body ${JSON.stringify(await response.clone().text())}`);
            }
        },
    };
}
