export type LogoutReason = "session-expired" | "token-revoked" | "manual";

export interface LogoutMessage {
  title: string;
  body: string;
  variant: "info" | "warning" | "error";
}

const STORAGE_KEY = "customer-portal:lastLogoutReason";

const LOGOUT_MESSAGES: Record<LogoutReason, LogoutMessage> = {
  "session-expired": {
    title: "Session Expired",
    body: "For your security, your session expired. Please sign in again to continue.",
    variant: "warning",
  },
  "token-revoked": {
    title: "Signed Out For Your Safety",
    body: "We detected a security change and signed you out. Please sign in again to verify your session.",
    variant: "error",
  },
  manual: {
    title: "Signed Out",
    body: "You have been signed out. Sign in again whenever you're ready.",
    variant: "info",
  },
};

export function setLogoutReason(reason: LogoutReason): void {
  if (typeof window === "undefined") return;
  try {
    sessionStorage.setItem(STORAGE_KEY, reason);
  } catch {
    // Ignore storage errors (e.g., private mode)
  }
}

export function clearLogoutReason(): void {
  if (typeof window === "undefined") return;
  try {
    sessionStorage.removeItem(STORAGE_KEY);
  } catch {
    // Ignore storage errors
  }
}

export function consumeLogoutReason(): LogoutReason | null {
  if (typeof window === "undefined") return null;
  try {
    const reason = sessionStorage.getItem(STORAGE_KEY) as LogoutReason | null;
    if (reason) {
      sessionStorage.removeItem(STORAGE_KEY);
      return reason;
    }
  } catch {
    // Ignore storage errors
  }
  return null;
}

export function logoutReasonFromErrorCode(code: string): LogoutReason | undefined {
  switch (code) {
    case "TOKEN_REVOKED":
    case "INVALID_REFRESH_TOKEN":
      return "token-revoked";
    case "SESSION_EXPIRED":
      return "session-expired";
    default:
      return undefined;
  }
}

export function resolveLogoutMessage(reason: LogoutReason): LogoutMessage {
  return LOGOUT_MESSAGES[reason] ?? LOGOUT_MESSAGES.manual;
}

export function isLogoutReason(value: string | null | undefined): value is LogoutReason {
  return value === "session-expired" || value === "token-revoked" || value === "manual";
}
