export type AuthScope = 'user' | 'admin'

export interface AuthTokenPair {
  access_token: string
  refresh_token: string
}

const userKeys = {
  accessToken: 'access_token',
  refreshToken: 'refresh_token',
  profile: ['user_id', 'phone', 'nickname', 'avatar_url', 'realname_status'],
}

const adminKeys = {
  accessToken: 'admin_access_token',
  refreshToken: 'admin_refresh_token',
  profile: ['admin_id', 'admin_username'],
}

function keysFor(scope: AuthScope) {
  return scope === 'admin' ? adminKeys : userKeys
}

export function getAccessToken(scope: AuthScope) {
  return localStorage.getItem(keysFor(scope).accessToken) || ''
}

export function getRefreshToken(scope: AuthScope) {
  return localStorage.getItem(keysFor(scope).refreshToken) || ''
}

export function setAuthTokens(scope: AuthScope, tokens: AuthTokenPair) {
  const keys = keysFor(scope)
  localStorage.setItem(keys.accessToken, tokens.access_token)
  localStorage.setItem(keys.refreshToken, tokens.refresh_token)
  notifyAuthStorageChanged(scope)
}

export function clearAuthStorage(scope: AuthScope) {
  const keys = keysFor(scope)
  localStorage.removeItem(keys.accessToken)
  localStorage.removeItem(keys.refreshToken)
  keys.profile.forEach((key) => localStorage.removeItem(key))
  notifyAuthStorageChanged(scope)
}

export function getLoginPath(scope: AuthScope, currentPath: string) {
  if (scope === 'admin') return '/admin/login'
  return currentPath.startsWith('/m') ? '/m/login' : '/login'
}

export function notifyAuthStorageChanged(scope: AuthScope) {
  window.dispatchEvent(new CustomEvent('auth-storage-changed', { detail: { scope } }))
}
