"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;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runInProd = exports.testAutomation = exports.getDB = exports.checkPermissionsEndpoint = exports.checkBuilderEndpoint = exports.createRequest = exports.clearAllAutomations = exports.clearAllApps = exports.getAllTableRows = void 0;
const rowController = __importStar(require("../../../controllers/row"));
const appController = __importStar(require("../../../controllers/application"));
const utils_1 = require("../../../../db/utils");
const roles_1 = require("@devlego/backend-core/roles");
const tenancy_1 = require("@devlego/backend-core/tenancy");
const structures_1 = require("../../../../tests/utilities/structures");
const context_1 = require("@devlego/backend-core/context");
const env = __importStar(require("../../../../environment"));
class Request {
    constructor(appId, params) {
        this.appId = appId;
        this.params = params;
        this.request = {};
    }
}
function runRequest(appId, controlFunc, request) {
    return (0, context_1.doInAppContext)(appId, () => __awaiter(this, void 0, void 0, function* () {
        return controlFunc(request);
    }));
}
const getAllTableRows = (config) => __awaiter(void 0, void 0, void 0, function* () {
    const req = new Request(config.appId, { tableId: config.table._id });
    yield runRequest(config.appId, rowController.fetch, req);
    return req.body;
});
exports.getAllTableRows = getAllTableRows;
const clearAllApps = (tenantId = structures_1.TENANT_ID) => __awaiter(void 0, void 0, void 0, function* () {
    yield (0, tenancy_1.doInTenant)(tenantId, () => __awaiter(void 0, void 0, void 0, function* () {
        const req = { query: { status: utils_1.AppStatus.DEV }, user: { tenantId } };
        yield appController.fetch(req);
        const apps = req.body;
        if (!apps || apps.length <= 0) {
            return;
        }
        for (let app of apps) {
            const { appId } = app;
            const req = new Request(null, { appId });
            yield runRequest(appId, appController.destroy, req);
        }
    }));
});
exports.clearAllApps = clearAllApps;
const clearAllAutomations = (config) => __awaiter(void 0, void 0, void 0, function* () {
    const automations = yield config.getAllAutomations();
    for (let auto of automations) {
        yield (0, context_1.doInAppContext)(config.appId, () => __awaiter(void 0, void 0, void 0, function* () {
            yield config.deleteAutomation(auto);
        }));
    }
});
exports.clearAllAutomations = clearAllAutomations;
const createRequest = (request, method, url, body) => {
    let req;
    if (method === "POST")
        req = request.post(url).send(body);
    else if (method === "GET")
        req = request.get(url);
    else if (method === "DELETE")
        req = request.delete(url);
    else if (method === "PATCH")
        req = request.patch(url).send(body);
    else if (method === "PUT")
        req = request.put(url).send(body);
    return req;
};
exports.createRequest = createRequest;
const checkBuilderEndpoint = ({ config, method, url, body, }) => __awaiter(void 0, void 0, void 0, function* () {
    const headers = yield config.login({
        userId: "us_fail",
        builder: false,
        prodApp: true,
    });
    yield exports
        .createRequest(config.request, method, url, body)
        .set(headers)
        .expect(403);
});
exports.checkBuilderEndpoint = checkBuilderEndpoint;
const checkPermissionsEndpoint = ({ config, method, url, body, passRole, failRole, }) => __awaiter(void 0, void 0, void 0, function* () {
    const passHeader = yield config.login({
        roleId: passRole,
        prodApp: true,
    });
    yield exports
        .createRequest(config.request, method, url, body)
        .set(passHeader)
        .expect(200);
    let failHeader;
    if (failRole === roles_1.BUILTIN_ROLE_IDS.PUBLIC) {
        failHeader = config.publicHeaders({ prodApp: true });
    }
    else {
        failHeader = yield config.login({
            roleId: failRole,
            builder: false,
            prodApp: true,
        });
    }
    yield exports
        .createRequest(config.request, method, url, body)
        .set(failHeader)
        .expect(403);
});
exports.checkPermissionsEndpoint = checkPermissionsEndpoint;
const getDB = () => {
    return (0, context_1.getAppDB)();
};
exports.getDB = getDB;
const testAutomation = (config, automation) => __awaiter(void 0, void 0, void 0, function* () {
    return runRequest(automation.appId, () => __awaiter(void 0, void 0, void 0, function* () {
        return yield config.request
            .post(`/api/automations/${automation._id}/test`)
            .send({
            row: {
                name: "Test",
                description: "TEST",
            },
        })
            .set(config.defaultHeaders())
            .expect("Content-Type", /json/)
            .expect(200);
    }));
});
exports.testAutomation = testAutomation;
const runInProd = (func) => __awaiter(void 0, void 0, void 0, function* () {
    const nodeEnv = env.NODE_ENV;
    const workerId = env.JEST_WORKER_ID;
    env._set("NODE_ENV", "PRODUCTION");
    env._set("JEST_WORKER_ID", null);
    yield func();
    env._set("NODE_ENV", nodeEnv);
    env._set("JEST_WORKER_ID", workerId);
});
exports.runInProd = runInProd;
