import GlobalConfigService from "../Services/GlobalConfigService";
import Response from "../Utils/Response";
import BaseAPI from "./BaseAPI";
import GlobalConfig from "../../Models/DatabaseModels/GlobalConfig";
import ObjectID from "../../Types/ObjectID";
import BadDataException from "../../Types/Exception/BadDataException";
import API from "../../Utils/API";
import HTTPErrorResponse from "../../Types/API/HTTPErrorResponse";
import { EnterpriseLicenseValidationUrl } from "../EnvironmentConfig";
import UserMiddleware from "../Middleware/UserAuthorization";
export default class GlobalConfigAPI extends BaseAPI {
    constructor() {
        var _a, _b, _c;
        super(GlobalConfig, GlobalConfigService);
        this.router.get(`${(_a = new this.entityType().getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/vars`, async (req, res, next) => {
            try {
                const globalConfig = await GlobalConfigService.findOneById({
                    id: ObjectID.getZeroObjectID(),
                    select: {
                        disableUserProjectCreation: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                return Response.sendJsonObjectResponse(req, res, {
                    disableUserProjectCreation: Boolean(globalConfig === null || globalConfig === void 0 ? void 0 : globalConfig.disableUserProjectCreation),
                });
            }
            catch (err) {
                next(err);
            }
        });
        this.router.get(`${(_b = new this.entityType().getCrudApiPath()) === null || _b === void 0 ? void 0 : _b.toString()}/license`, async (req, res, next) => {
            try {
                const config = await GlobalConfigService.findOneById({
                    id: ObjectID.getZeroObjectID(),
                    select: {
                        enterpriseCompanyName: true,
                        enterpriseLicenseExpiresAt: true,
                        enterpriseLicenseKey: true,
                        enterpriseLicenseToken: true,
                        enterpriseLicenseUserLimit: true,
                        enterpriseLicenseCurrentUserCount: true,
                        enterpriseLicenseUserCountUpdatedAt: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                const responseBody = {
                    companyName: (config === null || config === void 0 ? void 0 : config.enterpriseCompanyName) || null,
                    expiresAt: (config === null || config === void 0 ? void 0 : config.enterpriseLicenseExpiresAt)
                        ? config.enterpriseLicenseExpiresAt.toISOString()
                        : null,
                    licenseKey: (config === null || config === void 0 ? void 0 : config.enterpriseLicenseKey) || null,
                    token: (config === null || config === void 0 ? void 0 : config.enterpriseLicenseToken) || null,
                    userLimit: typeof (config === null || config === void 0 ? void 0 : config.enterpriseLicenseUserLimit) === "number"
                        ? config.enterpriseLicenseUserLimit
                        : null,
                    currentUserCount: typeof (config === null || config === void 0 ? void 0 : config.enterpriseLicenseCurrentUserCount) === "number"
                        ? config.enterpriseLicenseCurrentUserCount
                        : null,
                    userCountUpdatedAt: (config === null || config === void 0 ? void 0 : config.enterpriseLicenseUserCountUpdatedAt)
                        ? config.enterpriseLicenseUserCountUpdatedAt.toISOString()
                        : null,
                };
                return Response.sendJsonObjectResponse(req, res, responseBody);
            }
            catch (err) {
                next(err);
            }
        });
        this.router.post(`${(_c = new this.entityType().getCrudApiPath()) === null || _c === void 0 ? void 0 : _c.toString()}/license`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            var _a, _b, _c;
            try {
                const licenseKey = ((_a = req.body["licenseKey"]) === null || _a === void 0 ? void 0 : _a.trim()) || "";
                if (!licenseKey) {
                    throw new BadDataException("License key is required");
                }
                const validationResponse = await API.post({
                    url: EnterpriseLicenseValidationUrl,
                    data: {
                        licenseKey,
                    },
                });
                if (!validationResponse.isSuccess()) {
                    const errorMessage = validationResponse instanceof HTTPErrorResponse
                        ? validationResponse.message ||
                            "Failed to validate license key."
                        : "Failed to validate license key.";
                    throw new BadDataException(errorMessage);
                }
                const payload = validationResponse.data;
                const companyNameRaw = ((_b = payload["companyName"]) === null || _b === void 0 ? void 0 : _b.trim()) || "";
                const expiresAtRaw = payload["expiresAt"] || "";
                const licenseKeyRaw = ((_c = payload["licenseKey"]) === null || _c === void 0 ? void 0 : _c.trim()) || licenseKey;
                const licenseToken = payload["token"] || "";
                let licenseExpiry = undefined;
                if (expiresAtRaw) {
                    const parsedDate = new Date(expiresAtRaw);
                    if (Number.isNaN(parsedDate.getTime())) {
                        throw new BadDataException("License expiration returned from server is invalid.");
                    }
                    licenseExpiry = parsedDate;
                }
                const userLimitRaw = payload["userLimit"];
                const userLimit = typeof userLimitRaw === "number" && Number.isFinite(userLimitRaw)
                    ? userLimitRaw
                    : null;
                const currentUserCountRaw = payload["currentUserCount"];
                const currentUserCount = typeof currentUserCountRaw === "number" &&
                    Number.isFinite(currentUserCountRaw)
                    ? currentUserCountRaw
                    : null;
                const userCountUpdatedAtRaw = payload["userCountUpdatedAt"];
                let userCountUpdatedAt = null;
                if (userCountUpdatedAtRaw) {
                    const parsedReportedAt = new Date(userCountUpdatedAtRaw);
                    if (!Number.isNaN(parsedReportedAt.getTime())) {
                        userCountUpdatedAt = parsedReportedAt;
                    }
                }
                const updatePayload = {
                    enterpriseCompanyName: companyNameRaw || null,
                    enterpriseLicenseKey: licenseKeyRaw || null,
                    enterpriseLicenseExpiresAt: licenseExpiry || null,
                    enterpriseLicenseToken: licenseToken || null,
                    enterpriseLicenseUserLimit: userLimit,
                    enterpriseLicenseCurrentUserCount: currentUserCount,
                    enterpriseLicenseUserCountUpdatedAt: userCountUpdatedAt,
                };
                const globalConfigId = ObjectID.getZeroObjectID();
                const existingConfig = await GlobalConfigService.findOneById({
                    id: globalConfigId,
                    select: {
                        _id: true,
                    },
                    props: {
                        isRoot: true,
                        ignoreHooks: true,
                    },
                });
                if (existingConfig) {
                    await GlobalConfigService.updateOneById({
                        id: globalConfigId,
                        data: updatePayload,
                        props: {
                            isRoot: true,
                            ignoreHooks: true,
                        },
                    });
                }
                else {
                    const newConfig = new GlobalConfig();
                    newConfig.id = globalConfigId;
                    if (companyNameRaw) {
                        newConfig.enterpriseCompanyName = companyNameRaw;
                    }
                    if (licenseKeyRaw) {
                        newConfig.enterpriseLicenseKey = licenseKeyRaw;
                    }
                    if (licenseToken) {
                        newConfig.enterpriseLicenseToken = licenseToken;
                    }
                    if (licenseExpiry) {
                        newConfig.enterpriseLicenseExpiresAt = licenseExpiry;
                    }
                    if (userLimit !== null) {
                        newConfig.enterpriseLicenseUserLimit = userLimit;
                    }
                    if (currentUserCount !== null) {
                        newConfig.enterpriseLicenseCurrentUserCount = currentUserCount;
                    }
                    if (userCountUpdatedAt) {
                        newConfig.enterpriseLicenseUserCountUpdatedAt =
                            userCountUpdatedAt;
                    }
                    await GlobalConfigService.create({
                        data: newConfig,
                        props: {
                            isRoot: true,
                            ignoreHooks: true,
                        },
                    });
                }
                return Response.sendJsonObjectResponse(req, res, {
                    companyName: companyNameRaw || null,
                    expiresAt: licenseExpiry ? licenseExpiry.toISOString() : null,
                    licenseKey: licenseKeyRaw || null,
                    token: licenseToken || null,
                    userLimit: userLimit,
                    currentUserCount: currentUserCount,
                    userCountUpdatedAt: userCountUpdatedAt
                        ? userCountUpdatedAt.toISOString()
                        : null,
                });
            }
            catch (err) {
                next(err);
            }
        });
    }
}
//# sourceMappingURL=GlobalConfigAPI.js.map