import EnterpriseLicense from "../../Models/DatabaseModels/EnterpriseLicense";
import BadDataException from "../../Types/Exception/BadDataException";
import EnterpriseLicenseService from "../Services/EnterpriseLicenseService";
import UserMiddleware from "../Middleware/UserAuthorization";
import JSONWebToken from "../Utils/JsonWebToken";
import OneUptimeDate from "../../Types/Date";
import Response from "../Utils/Response";
import BaseAPI from "./BaseAPI";
// import { Host } from "../EnvironmentConfig";
export default class EnterpriseLicenseAPI extends BaseAPI {
    constructor() {
        var _a, _b;
        super(EnterpriseLicense, EnterpriseLicenseService);
        this.router.post(`${(_a = new this.entityType().getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/validate`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                const licenseKey = req.body["licenseKey"];
                if (!licenseKey) {
                    throw new BadDataException("License key is required");
                }
                //const serverHost: string = Host.toString();
                /*
                 * if (!serverHost.includes("oneuptime.com")) {
                 *   throw new BadDataException(
                 *     "Enterprise license validation is only available on oneuptime.com",
                 *   );
                 * }
                 */
                const license = await EnterpriseLicenseService.findOneBy({
                    query: {
                        licenseKey: licenseKey,
                    },
                    select: {
                        companyName: true,
                        expiresAt: true,
                        licenseKey: true,
                        userLimit: true,
                        currentUserCount: true,
                        userCountUpdatedAt: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                if (!license) {
                    throw new BadDataException("License key is invalid");
                }
                if (!license.expiresAt) {
                    throw new BadDataException("License expiration is not set");
                }
                const now = Date.now();
                const expiresAtMs = license.expiresAt.getTime();
                const secondsUntilExpiry = Math.floor((expiresAtMs - now) / 1000);
                if (secondsUntilExpiry <= 0) {
                    throw new BadDataException("License key has expired");
                }
                const payload = {
                    companyName: license.companyName || "",
                    expiresAt: license.expiresAt.toISOString(),
                    licenseKey: license.licenseKey || "",
                    userLimit: typeof license.userLimit === "number" ? license.userLimit : null,
                };
                const token = JSONWebToken.signJsonPayload(payload, Math.max(secondsUntilExpiry, 1));
                return Response.sendJsonObjectResponse(req, res, {
                    companyName: payload["companyName"],
                    expiresAt: payload["expiresAt"],
                    licenseKey: payload["licenseKey"],
                    userLimit: payload["userLimit"],
                    currentUserCount: typeof license.currentUserCount === "number"
                        ? license.currentUserCount
                        : null,
                    userCountUpdatedAt: license.userCountUpdatedAt
                        ? license.userCountUpdatedAt.toISOString()
                        : null,
                    token,
                });
            }
            catch (err) {
                next(err);
            }
        });
        this.router.post(`${(_b = new this.entityType().getCrudApiPath()) === null || _b === void 0 ? void 0 : _b.toString()}/report-user-count`, async (req, res, next) => {
            var _a;
            try {
                const licenseKey = (_a = req.body["licenseKey"]) === null || _a === void 0 ? void 0 : _a.trim();
                const rawUserCount = req.body["userCount"];
                if (!licenseKey) {
                    throw new BadDataException("License key is required");
                }
                const userCount = Number(rawUserCount);
                if (!Number.isFinite(userCount) ||
                    userCount < 0 ||
                    !Number.isInteger(userCount)) {
                    throw new BadDataException("userCount must be a non-negative integer");
                }
                const license = await EnterpriseLicenseService.findOneBy({
                    query: {
                        licenseKey: licenseKey,
                    },
                    select: {
                        _id: true,
                        userLimit: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                if (!license) {
                    throw new BadDataException("License key is invalid");
                }
                const reportedAt = OneUptimeDate.getCurrentDate();
                await EnterpriseLicenseService.updateOneById({
                    id: license.id,
                    data: {
                        currentUserCount: userCount,
                        userCountUpdatedAt: reportedAt,
                    },
                    props: {
                        isRoot: true,
                        ignoreHooks: true,
                    },
                });
                return Response.sendJsonObjectResponse(req, res, {
                    currentUserCount: userCount,
                    userCountUpdatedAt: reportedAt.toISOString(),
                    userLimit: typeof license.userLimit === "number" ? license.userLimit : null,
                });
            }
            catch (err) {
                next(err);
            }
        });
    }
}
//# sourceMappingURL=EnterpriseLicenseAPI.js.map