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 ObjectID from "../../Types/ObjectID";
import JSONWebToken from "./JsonWebToken";
import OneUptimeDate from "../../Types/Date";
import PositiveNumber from "../../Types/PositiveNumber";
import CookieName from "../../Types/CookieName";
import { MASTER_PASSWORD_COOKIE_IDENTIFIER, MASTER_PASSWORD_COOKIE_MAX_AGE_IN_DAYS, } from "../../Types/StatusPage/MasterPassword";
import { DASHBOARD_MASTER_PASSWORD_COOKIE_IDENTIFIER, DASHBOARD_MASTER_PASSWORD_COOKIE_MAX_AGE_IN_DAYS, } from "../../Types/Dashboard/MasterPassword";
import CaptureSpan from "./Telemetry/CaptureSpan";
class CookieUtil {
    static getCookiesFromCookieString(cookieString) {
        const cookies = {};
        cookieString.split(";").forEach((cookie) => {
            const parts = cookie.split("=");
            const key = parts[0].trim();
            const value = parts[1];
            cookies[key] = value;
        });
        return cookies;
    }
    static setSSOCookie(data) {
        const { user, projectId, expressResponse: res } = data;
        const ssoToken = JSONWebToken.sign({
            data: {
                userId: user.id,
                projectId: projectId,
                name: user.name,
                email: user.email,
                isMasterAdmin: false,
                isGeneralLogin: false,
            },
            expiresInSeconds: OneUptimeDate.getSecondsInDays(new PositiveNumber(30)),
        });
        CookieUtil.setCookie(res, CookieUtil.getUserSSOKey(projectId), ssoToken, {
            maxAge: OneUptimeDate.getMillisecondsInDays(new PositiveNumber(30)),
            httpOnly: true,
        });
    }
    static setUserCookie(data) {
        var _a, _b, _c, _d, _e;
        const { expressResponse: res, user, isGlobalLogin, sessionId, refreshToken, refreshTokenExpiresAt, } = data;
        const accessTokenExpiresInSeconds = data.accessTokenExpiresInSeconds ||
            CookieUtil.DEFAULT_ACCESS_TOKEN_EXPIRY_SECONDS;
        const token = JSONWebToken.signUserLoginToken({
            tokenData: {
                userId: user.id,
                email: user.email,
                name: user.name,
                timezone: user.timezone || null,
                isMasterAdmin: user.isMasterAdmin,
                isGlobalLogin: isGlobalLogin, // This is a general login without SSO. So, we will set this to true. This will give access to all the projects that dont require SSO.
                sessionId: sessionId,
            },
            expiresInSeconds: accessTokenExpiresInSeconds,
        });
        // Set a cookie with token.
        CookieUtil.setCookie(res, CookieUtil.getUserTokenKey(), token, {
            maxAge: accessTokenExpiresInSeconds * 1000,
            httpOnly: true,
        });
        const refreshTokenTtl = Math.max(refreshTokenExpiresAt.getTime() - Date.now(), 0);
        CookieUtil.setCookie(res, CookieUtil.getRefreshTokenKey(), refreshToken, {
            maxAge: refreshTokenTtl,
            httpOnly: true,
        });
        if (user.id) {
            // set user id cookie
            CookieUtil.setCookie(res, CookieName.UserID, user.id.toString(), {
                maxAge: OneUptimeDate.getMillisecondsInDays(new PositiveNumber(30)),
                httpOnly: false,
            });
        }
        if (user.email) {
            // set user email cookie
            CookieUtil.setCookie(res, CookieName.Email, ((_a = user.email) === null || _a === void 0 ? void 0 : _a.toString()) || "", {
                maxAge: OneUptimeDate.getMillisecondsInDays(new PositiveNumber(30)),
                httpOnly: false,
            });
        }
        if (user.name) {
            // set user name cookie
            CookieUtil.setCookie(res, CookieName.Name, ((_b = user.name) === null || _b === void 0 ? void 0 : _b.toString()) || "", {
                maxAge: OneUptimeDate.getMillisecondsInDays(new PositiveNumber(30)),
                httpOnly: false,
            });
        }
        if (user.timezone) {
            // set user timezone cookie
            CookieUtil.setCookie(res, CookieName.Timezone, ((_c = user.timezone) === null || _c === void 0 ? void 0 : _c.toString()) || "", {
                maxAge: OneUptimeDate.getMillisecondsInDays(new PositiveNumber(30)),
                httpOnly: false,
            });
        }
        if (user.isMasterAdmin) {
            // set user isMasterAdmin cookie
            CookieUtil.setCookie(res, CookieName.IsMasterAdmin, ((_d = user.isMasterAdmin) === null || _d === void 0 ? void 0 : _d.toString()) || "", {
                maxAge: OneUptimeDate.getMillisecondsInDays(new PositiveNumber(30)),
                httpOnly: false,
            });
        }
        if (user.profilePictureId) {
            // set user profile picture id cookie
            CookieUtil.setCookie(res, CookieName.ProfilePicID, ((_e = user.profilePictureId) === null || _e === void 0 ? void 0 : _e.toString()) || "", {
                maxAge: OneUptimeDate.getMillisecondsInDays(new PositiveNumber(30)),
                httpOnly: false,
            });
        }
    }
    static setStatusPagePrivateUserCookie(data) {
        const { expressResponse: res, user, statusPageId, sessionId, refreshToken, refreshTokenExpiresAt, } = data;
        const accessTokenExpiresInSeconds = data.accessTokenExpiresInSeconds ||
            CookieUtil.DEFAULT_ACCESS_TOKEN_EXPIRY_SECONDS;
        const token = JSONWebToken.sign({
            data: {
                userId: user.id,
                email: user.email,
                statusPageId: statusPageId,
                sessionId: sessionId,
            },
            expiresInSeconds: accessTokenExpiresInSeconds,
        });
        CookieUtil.setCookie(res, CookieUtil.getUserTokenKey(statusPageId), token, {
            maxAge: accessTokenExpiresInSeconds * 1000,
            httpOnly: true,
        });
        const refreshTokenTtl = Math.max(refreshTokenExpiresAt.getTime() - Date.now(), 0);
        CookieUtil.setCookie(res, CookieUtil.getRefreshTokenKey(statusPageId), refreshToken, {
            maxAge: refreshTokenTtl,
            httpOnly: true,
        });
        return token;
    }
    static setStatusPageMasterPasswordCookie(data) {
        const expiresInDays = new PositiveNumber(MASTER_PASSWORD_COOKIE_MAX_AGE_IN_DAYS);
        const token = JSONWebToken.signJsonPayload({
            statusPageId: data.statusPageId.toString(),
            type: MASTER_PASSWORD_COOKIE_IDENTIFIER,
        }, OneUptimeDate.getSecondsInDays(expiresInDays));
        CookieUtil.setCookie(data.expressResponse, CookieUtil.getStatusPageMasterPasswordKey(data.statusPageId), token, {
            maxAge: OneUptimeDate.getMillisecondsInDays(expiresInDays),
            httpOnly: true,
        });
    }
    static setCookie(res, name, value, options) {
        const cookieOptions = Object.assign({ path: "/", sameSite: "lax" }, options);
        res.cookie(name, value, cookieOptions);
    }
    // get cookie with express request
    static getCookieFromExpressRequest(req, name) {
        return req.cookies[name];
    }
    static getRefreshTokenFromExpressRequest(req, id) {
        return CookieUtil.getCookieFromExpressRequest(req, CookieUtil.getRefreshTokenKey(id));
    }
    // delete cookie with express response
    static removeCookie(res, name) {
        res.clearCookie(name, {
            path: "/",
            sameSite: "lax",
        });
    }
    static removeStatusPageMasterPasswordCookie(res, statusPageId) {
        CookieUtil.removeCookie(res, CookieUtil.getStatusPageMasterPasswordKey(statusPageId));
    }
    static setDashboardMasterPasswordCookie(data) {
        const expiresInDays = new PositiveNumber(DASHBOARD_MASTER_PASSWORD_COOKIE_MAX_AGE_IN_DAYS);
        const token = JSONWebToken.signJsonPayload({
            dashboardId: data.dashboardId.toString(),
            type: DASHBOARD_MASTER_PASSWORD_COOKIE_IDENTIFIER,
        }, OneUptimeDate.getSecondsInDays(expiresInDays));
        CookieUtil.setCookie(data.expressResponse, CookieUtil.getDashboardMasterPasswordKey(data.dashboardId), token, {
            maxAge: OneUptimeDate.getMillisecondsInDays(expiresInDays),
            httpOnly: true,
        });
    }
    static removeDashboardMasterPasswordCookie(res, dashboardId) {
        CookieUtil.removeCookie(res, CookieUtil.getDashboardMasterPasswordKey(dashboardId));
    }
    static getDashboardMasterPasswordKey(id) {
        return `${CookieName.DashboardMasterPassword}-${id.toString()}`;
    }
    // get all cookies with express request
    static getAllCookies(req) {
        return req.cookies || {};
    }
    static getUserTokenKey(id) {
        if (!id) {
            return CookieName.Token;
        }
        return `${CookieName.Token}-${id.toString()}`;
    }
    static getRefreshTokenKey(id) {
        if (!id) {
            return CookieName.RefreshToken;
        }
        return `${CookieName.RefreshToken}-${id.toString()}`;
    }
    static getStatusPageMasterPasswordKey(id) {
        return `${CookieName.StatusPageMasterPassword}-${id.toString()}`;
    }
    static getUserSSOKey(id) {
        return `${this.getSSOKey()}${id.toString()}`;
    }
    static getSSOKey() {
        return `sso-`;
    }
    // delete all cookies.
    static removeAllCookies(req, res) {
        const cookies = this.getAllCookies(req);
        for (const key in cookies) {
            this.removeCookie(res, key);
        }
        // Always attempt to remove refresh token cookie even if not parsed.
        this.removeCookie(res, this.getRefreshTokenKey());
    }
}
// set cookie with express response
CookieUtil.DEFAULT_ACCESS_TOKEN_EXPIRY_SECONDS = 15 * 60;
export default CookieUtil;
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Object)
], CookieUtil, "getCookiesFromCookieString", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], CookieUtil, "setSSOCookie", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], CookieUtil, "setUserCookie", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", String)
], CookieUtil, "setStatusPagePrivateUserCookie", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], CookieUtil, "setStatusPageMasterPasswordCookie", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, String, String, Object]),
    __metadata("design:returntype", void 0)
], CookieUtil, "setCookie", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, String]),
    __metadata("design:returntype", Object)
], CookieUtil, "getCookieFromExpressRequest", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, ObjectID]),
    __metadata("design:returntype", Object)
], CookieUtil, "getRefreshTokenFromExpressRequest", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, String]),
    __metadata("design:returntype", void 0)
], CookieUtil, "removeCookie", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, ObjectID]),
    __metadata("design:returntype", void 0)
], CookieUtil, "removeStatusPageMasterPasswordCookie", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], CookieUtil, "setDashboardMasterPasswordCookie", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, ObjectID]),
    __metadata("design:returntype", void 0)
], CookieUtil, "removeDashboardMasterPasswordCookie", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID]),
    __metadata("design:returntype", String)
], CookieUtil, "getDashboardMasterPasswordKey", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Object)
], CookieUtil, "getAllCookies", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID]),
    __metadata("design:returntype", String)
], CookieUtil, "getUserTokenKey", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID]),
    __metadata("design:returntype", String)
], CookieUtil, "getRefreshTokenKey", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID]),
    __metadata("design:returntype", String)
], CookieUtil, "getStatusPageMasterPasswordKey", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID]),
    __metadata("design:returntype", String)
], CookieUtil, "getUserSSOKey", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", String)
], CookieUtil, "getSSOKey", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", void 0)
], CookieUtil, "removeAllCookies", null);
//# sourceMappingURL=Cookie.js.map