/*
 * Copyright (c) 2025-2025 Broadcom. All Rights Reserved. Broadcom Confidential. The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
 */

export class DecodedJwt {
    header: Record<string, any>;
    payload: Record<string, any>;
    signature: string;

    constructor(private rawToken: string) {
        const parts = rawToken.split(".");
        if (parts.length !== 3) {
            throw new Error(`Invalid JWT format: '${rawToken}'`);
        }

        this.header = this.decodeBase64Url(parts[0]);
        this.payload = this.decodeBase64Url(parts[1]);
        this.signature = parts[2];
    }

    private decodeBase64Url(base64Url: string): Record<string, any> {
        const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
        const json = decodeURIComponent(Array.prototype.map.call(atob(base64), escapeMultibyteCharacter).join(""));
        return JSON.parse(json);
    }

    toJSON(): Record<string, any> {
        return {
            header: this.header,
            payload: this.payload,
            signature: this.signature,
        };
    }
}

function escapeMultibyteCharacter(c: string): string {
    return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
}
