const TOKEN_KEY = 'vehicle-platform.access-token';
export const PLATFORM_UNAUTHORIZED_EVENT = 'vehicle-platform:unauthorized';

export type PlatformSession = SessionInfo;

export function getAccessToken() {
  return window.sessionStorage.getItem(TOKEN_KEY) ?? '';
}

export function setAccessToken(token: string) {
  const normalized = token.trim();
  if (normalized) window.sessionStorage.setItem(TOKEN_KEY, normalized);
  else window.sessionStorage.removeItem(TOKEN_KEY);
}

export function clearAccessToken() {
  window.sessionStorage.removeItem(TOKEN_KEY);
}

export function notifyUnauthorizedSession(rejectedToken: string) {
  if (!rejectedToken || getAccessToken() !== rejectedToken) return false;
  clearAccessToken();
  window.dispatchEvent(new Event(PLATFORM_UNAUTHORIZED_EVENT));
  return true;
}

export function canOperate(session: PlatformSession) {
  return session.role === 'operator' || session.role === 'admin';
}

export function hasMenu(session: PlatformSession, menu: string) {
  if (session.role === 'admin') return true;
  if (!session.menuKeys) return session.role !== 'customer';
  return session.menuKeys.includes(menu);
}

export function canAdminister(session: PlatformSession) {
  return session.role === 'admin';
}
import type { SessionInfo } from '../../api/types';
