/**
 * Authentication Utilities
 *
 * This module provides utilities for handling authentication tokens,
 * including JWT detection and authorization header generation.
 */
export function isJwt(token) {
    // JWT tokens have exactly 3 parts separated by dots
    const parts = token.split(".");
    if (parts.length !== 3) {
        return false;
    }
    // Each part should be base64url encoded (no padding)
    // Basic validation - each part should be non-empty and contain valid base64url characters
    const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
    return parts.every((part) => part.length > 0 && base64UrlPattern.test(part));
}
/**
 * Parse a JWT token into its three parts
 * Returns the parts array if valid, null otherwise
 */
function parseJwt(token) {
    if (!isJwt(token)) {
        return null;
    }
    return token.split(".");
}
export function getAuthorizationHeader(token) {
    // Check if token is a JWT (has 3 parts separated by dots)
    if (isJwt(token)) {
        return `JWT ${token}`;
    }
    // Default to Bearer for other token types
    return `Bearer ${token}`;
}
// Handles nested service-JWT shape (`sub_type: "service"` with `njwt`). Lenient — falls back to outer payload on nested parse failure.
function readJwtPayload(token) {
    const parts = parseJwt(token);
    if (!parts)
        return null;
    let payload;
    try {
        payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf-8"));
    }
    catch {
        return null;
    }
    if (payload["sub_type"] === "service" &&
        typeof payload["njwt"] === "string") {
        const nestedParts = parseJwt(payload["njwt"]);
        if (nestedParts) {
            try {
                return JSON.parse(Buffer.from(nestedParts[1], "base64url").toString("utf-8"));
            }
            catch {
                // Fall through to outer payload.
            }
        }
    }
    return payload;
}
/** Never throws — an auth decode error must not take down request telemetry. */
export function extractUserIdsFromJwt(token) {
    const payload = readJwtPayload(token);
    if (!payload) {
        return { customuser_id: null, account_id: null };
    }
    const accRaw = payload["zap:acc"];
    const accountId = accRaw != null ? parseInt(String(accRaw), 10) : null;
    const customUserId = payload["sub_type"] === "customuser" && payload["sub"] != null
        ? parseInt(String(payload["sub"]), 10)
        : null;
    return {
        customuser_id: customUserId !== null && !isNaN(customUserId) ? customUserId : null,
        account_id: accountId !== null && !isNaN(accountId) ? accountId : null,
    };
}
