import { ADMIN_LOGIN_PATH } from '@/shared/utils/adminPath'

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', 'admin_support_status', 'admin_password_must_change'],
}

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

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

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

export function setAuthTokens(scope: AuthScope, tokens: AuthTokenPair) {
  const keys = keysFor(scope)
  if (scope === 'admin') {
    localStorage.removeItem(keys.accessToken)
    localStorage.removeItem(keys.refreshToken)
    notifyAuthStorageChanged(scope)
    return
  }
  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_PATH
  return currentPath.startsWith('/m') ? '/m/login' : '/login'
}

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