var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { EncryptionSecret } from "../EnvironmentConfig";
import Email from "../../Types/Email";
import BadDataException from "../../Types/Exception/BadDataException";
import JSONFunctions from "../../Types/JSONFunctions";
import Name from "../../Types/Name";
import ObjectID from "../../Types/ObjectID";
import StatusPagePrivateUser from "../../Models/DatabaseModels/StatusPagePrivateUser";
import User from "../../Models/DatabaseModels/User";
import jwt from "jsonwebtoken";
import logger from "./Logger";
import CaptureSpan from "./Telemetry/CaptureSpan";
class JSONWebToken {
    static signUserLoginToken(data) {
        return JSONWebToken.sign({
            data: data.tokenData,
            expiresInSeconds: data.expiresInSeconds,
        });
    }
    static sign(props) {
        var _a, _b, _c, _d, _e, _f, _g;
        const { data, expiresInSeconds } = props;
        let jsonObj;
        if (typeof data === "string") {
            jsonObj = {
                data: data.toString(),
            };
        }
        else if (data instanceof User) {
            jsonObj = {
                userId: data.id.toString(),
                email: data.email.toString(),
                name: ((_a = data.name) === null || _a === void 0 ? void 0 : _a.toString()) || "",
                isMasterAdmin: data.isMasterAdmin,
            };
        }
        else if (data instanceof StatusPagePrivateUser) {
            jsonObj = {
                userId: data.id.toString(),
                email: data.email.toString(),
                statusPageId: (_b = data.statusPageId) === null || _b === void 0 ? void 0 : _b.toString(),
            };
        }
        else {
            jsonObj = Object.assign(Object.assign({}, data), { userId: (_c = data.userId) === null || _c === void 0 ? void 0 : _c.toString(), email: (_d = data.email) === null || _d === void 0 ? void 0 : _d.toString(), name: ((_e = data.name) === null || _e === void 0 ? void 0 : _e.toString()) || "", projectId: ((_f = data.projectId) === null || _f === void 0 ? void 0 : _f.toString()) || "", isMasterAdmin: data.isMasterAdmin, sessionId: ((_g = data.sessionId) === null || _g === void 0 ? void 0 : _g.toString()) || undefined });
        }
        return JSONWebToken.signJsonPayload(jsonObj, expiresInSeconds);
    }
    static signJsonPayload(payload, expiresInSeconds) {
        return jwt.sign(payload, EncryptionSecret.toString(), {
            expiresIn: expiresInSeconds,
        });
    }
    /**
     * Sign a JWT with a custom private key using RS256 algorithm.
     * Used for OAuth JWT Bearer flows that require asymmetric signing.
     */
    static signWithPrivateKey(payload, privateKey) {
        return jwt.sign(payload, privateKey, {
            algorithm: "RS256",
        });
    }
    static decodeJsonPayload(token) {
        const decodedToken = JSON.stringify(jwt.verify(token, EncryptionSecret.toString()));
        const decoded = JSONFunctions.parseJSONObject(decodedToken);
        return decoded;
    }
    static decode(token) {
        try {
            const decoded = JSONWebToken.decodeJsonPayload(token);
            if (decoded["statusPageId"]) {
                return {
                    userId: new ObjectID(decoded["userId"]),
                    email: new Email(decoded["email"]),
                    statusPageId: new ObjectID(decoded["statusPageId"]),
                    isMasterAdmin: false,
                    name: new Name("User"),
                    isGlobalLogin: Boolean(decoded["isGlobalLogin"]),
                    sessionId: decoded["sessionId"]
                        ? new ObjectID(decoded["sessionId"])
                        : undefined,
                };
            }
            return {
                userId: new ObjectID(decoded["userId"]),
                email: new Email(decoded["email"]),
                name: new Name(decoded["name"]),
                projectId: decoded["projectId"]
                    ? new ObjectID(decoded["projectId"])
                    : undefined,
                isMasterAdmin: Boolean(decoded["isMasterAdmin"]),
                isGlobalLogin: Boolean(decoded["isGlobalLogin"]),
                sessionId: decoded["sessionId"]
                    ? new ObjectID(decoded["sessionId"])
                    : undefined,
            };
        }
        catch (e) {
            logger.error(e);
            throw new BadDataException("AccessToken is invalid or expired");
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", String)
], JSONWebToken, "signUserLoginToken", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", String)
], JSONWebToken, "sign", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Number]),
    __metadata("design:returntype", String)
], JSONWebToken, "signJsonPayload", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, String]),
    __metadata("design:returntype", String)
], JSONWebToken, "signWithPrivateKey", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Object)
], JSONWebToken, "decodeJsonPayload", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Object)
], JSONWebToken, "decode", null);
export default JSONWebToken;
//# sourceMappingURL=JsonWebToken.js.map