"use strict";
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());
    });
};
const fetch = require("node-fetch");
const env = require("../environment");
const { checkSlashesInUrl } = require("./index");
const { getProdAppID } = require("@devlego/backend-core/db");
const { updateAppRole } = require("./global");
const { Headers } = require("@devlego/backend-core/constants");
const { getTenantId, isTenantIdSet } = require("@devlego/backend-core/tenancy");
function request(ctx, request) {
    if (!request.headers) {
        request.headers = {};
    }
    if (!ctx) {
        request.headers[Headers.API_KEY] = env.INTERNAL_API_KEY;
        if (isTenantIdSet()) {
            request.headers[Headers.TENANT_ID] = getTenantId();
        }
    }
    if (request.body && Object.keys(request.body).length > 0) {
        request.headers["Content-Type"] = "application/json";
        request.body =
            typeof request.body === "object"
                ? JSON.stringify(request.body)
                : request.body;
    }
    else {
        delete request.body;
    }
    if (ctx && ctx.headers) {
        request.headers = ctx.headers;
    }
    return request;
}
function checkResponse(response, errorMsg, { ctx } = {}) {
    return __awaiter(this, void 0, void 0, function* () {
        if (response.status !== 200) {
            let error;
            try {
                error = yield response.json();
            }
            catch (err) {
                error = yield response.text();
            }
            const msg = `Unable to ${errorMsg} - ${error.message ? error.message : error}`;
            if (ctx) {
                ctx.throw(400, msg);
            }
            else {
                throw msg;
            }
        }
        return response.json();
    });
}
exports.request = request;
// have to pass in the tenant ID as this could be coming from an automation
exports.sendSmtpEmail = (to, from, subject, contents, automation) => __awaiter(void 0, void 0, void 0, function* () {
    // tenant ID will be set in header
    const response = yield fetch(checkSlashesInUrl(env.WORKER_URL + `/api/global/email/send`), request(null, {
        method: "POST",
        body: {
            email: to,
            from,
            contents,
            subject,
            purpose: "custom",
            automation,
        },
    }));
    return checkResponse(response, "send email");
});
exports.getGlobalSelf = (ctx, appId = null) => __awaiter(void 0, void 0, void 0, function* () {
    const endpoint = `/api/global/self`;
    const response = yield fetch(checkSlashesInUrl(env.WORKER_URL + endpoint), 
    // we don't want to use API key when getting self
    request(ctx, { method: "GET" }));
    let json = yield checkResponse(response, "get self globally", { ctx });
    if (appId) {
        json = updateAppRole(json);
    }
    return json;
});
exports.removeAppFromUserRoles = (ctx, appId) => __awaiter(void 0, void 0, void 0, function* () {
    const prodAppId = getProdAppID(appId);
    const response = yield fetch(checkSlashesInUrl(env.WORKER_URL + `/api/global/roles/${prodAppId}`), request(ctx, {
        method: "DELETE",
    }));
    return checkResponse(response, "remove app role");
});
exports.allGlobalUsers = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield fetch(checkSlashesInUrl(env.WORKER_URL + "/api/global/users"), 
    // we don't want to use API key when getting self
    request(ctx, { method: "GET" }));
    return checkResponse(response, "get users", { ctx });
});
exports.saveGlobalUser = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield fetch(checkSlashesInUrl(env.WORKER_URL + "/api/global/users"), 
    // we don't want to use API key when getting self
    request(ctx, { method: "POST", body: ctx.request.body }));
    return checkResponse(response, "save user", { ctx });
});
exports.deleteGlobalUser = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield fetch(checkSlashesInUrl(env.WORKER_URL + `/api/global/users/${ctx.params.userId}`), 
    // we don't want to use API key when getting self
    request(ctx, { method: "DELETE" }));
    return checkResponse(response, "delete user", { ctx, body: ctx.request.body });
});
exports.readGlobalUser = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield fetch(checkSlashesInUrl(env.WORKER_URL + `/api/global/users/${ctx.params.userId}`), 
    // we don't want to use API key when getting self
    request(ctx, { method: "GET" }));
    return checkResponse(response, "get user", { ctx });
});
exports.createAdminUser = (email, password, tenantId) => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield fetch(checkSlashesInUrl(env.WORKER_URL + "/api/global/users/init"), request(null, { method: "POST", body: { email, password, tenantId } }));
    return checkResponse(response, "create admin user");
});
exports.getChecklist = () => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield fetch(checkSlashesInUrl(env.WORKER_URL + "/api/global/configs/checklist"), request(null, { method: "GET" }));
    return checkResponse(response, "get checklist");
});
