/** Client-side JWT payload decode (no signature verification). */

export function decodeJwtPayload(token) {
  if (!token || typeof token !== "string") return null;
  const parts = token.split(".");
  if (parts.length < 2) return null;
  try {
    const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
    const padded = base64 + "=".repeat((4 - (base64.length % 4)) % 4);
    const json = atob(padded);
    return JSON.parse(json);
  } catch {
    return null;
  }
}

export const JWT_PURPOSE = Object.freeze({
  LOGIN: "login",
  APP_LAUNCH: "app-launch",
  APP_SESSION: "app-session",
});

export const JWT_AUD = Object.freeze({
  MASTER: "master",
  SAT: "sat",
  RISK: "risk",
  SWI: "swi",
  PTW: "ptw",
});

export const SESSION_EXCHANGE_BY_AUD = Object.freeze({
  [JWT_AUD.SAT]: "/api/sat/auth/session",
  [JWT_AUD.RISK]: "/api/auth/session",
  [JWT_AUD.SWI]: "/api/swi/auth/session",
  [JWT_AUD.PTW]: "/api/ptw/auth/session",
});
