"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initBackendMocks = void 0;
/* eslint-disable no-console */
const nock_1 = __importDefault(require("nock"));
const url_1 = require("url");
const fs_1 = require("fs");
/* Loop through each mock and apply them to nock */
async function initBackendMocks() {
    const root = `${__dirname}/bridgeMocks`;
    await fs_1.promises.readdir(root).then(async (mocks) => {
        console.log(`Found ${mocks.length} to apply`);
        let appliedMocks = 0;
        for (const mock of mocks) {
            appliedMocks++;
            const backendMock = await fs_1.promises.readFile(`${root}/${mock}`);
            try {
                const jsonBackendMock = JSON.parse(backendMock.toString());
                applyBackendMock(jsonBackendMock);
            }
            catch (err) {
                console.log(err, mock);
            }
        }
        console.log(`Applied ${appliedMocks} out of ${mocks.length} files`);
    });
}
exports.initBackendMocks = initBackendMocks;
function applyBackendMock(mockContent) {
    const url = new url_1.URL(mockContent.request.url);
    const originWithoutPort = url.port && url.origin.includes(`:${url.port}`)
        ? url.origin.replace(`:${url.port}`, "")
        : url.origin;
    const endpoint = mockContent.request.url.replace(url.origin, "");
    switch (mockContent.request.method) {
        case "GET":
            (0, nock_1.default)(originWithoutPort)
                .persist()
                .get(endpoint)
                .reply(mockContent.response.statusCode, () => mockContent.response.body);
            break;
        case "POST":
            (0, nock_1.default)(originWithoutPort)
                .persist()
                .post(endpoint)
                .reply(mockContent.response.statusCode, () => mockContent.response.body);
            break;
        default:
            throw new Error("unknown method");
    }
}
exports.default = async () => {
    nock_1.default.disableNetConnect();
    await initBackendMocks();
};
//# sourceMappingURL=bridgeSetupUseMocks.js.map