import { ACCESS_TOKEN, REFRESH_TOKEN } from '@/constants';

export function getAccessToken(): string {
  return localStorage.getItem(ACCESS_TOKEN) || '';
}

export function setAccessToken(accessToken: string) {
  localStorage.setItem(ACCESS_TOKEN, accessToken);
}

export function removeAccessToken() {
  localStorage.removeItem(ACCESS_TOKEN);
}

export function getRefreshToken(): string {
  return localStorage.getItem(REFRESH_TOKEN) || '';
}

export function setRefreshToken(refreshToken: string) {
  localStorage.setItem(REFRESH_TOKEN, refreshToken);
}

export function removeRefreshToken() {
  localStorage.removeItem(REFRESH_TOKEN);
}

export function getBrowserId() {
  const id = localStorage.getItem('sip-browserid');
  if (!id) {
    const { navigator, screen } = window;
    let uid = '';
    uid += navigator?.mimeTypes?.length || '';
    uid += navigator?.userAgent.replace(/\D+/g, '') || '';
    uid += navigator?.plugins?.length || '';
    uid += screen?.height || '';
    uid += screen?.width || '';
    uid += screen?.pixelDepth || '';
    localStorage.setItem('sip-browserid', uid);
    return uid;
  }
  return id;
}

/**
 * Clear all localStorage data except browserId
 */
export function clearAllData() {
  const browserId = localStorage.getItem('sip-browserid');
  localStorage.clear();
  if (browserId) {
    localStorage.setItem('sip-browserid', browserId);
  }
}

/**
 * Clear all sessionStorage data
 */
export function clearSessionData() {
  sessionStorage.clear();
}
