export const AUTH_EVENT = "auth-change"

const TOKEN_KEY = "auth_token"
const USER_KEY = "auth_user"

export function readCookie(name: string): string | null {
  const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`))
  return match ? decodeURIComponent(match[1]) : null
}

export function clearCookie(name: string) {
  // biome-ignore lint/suspicious/noDocumentCookie: Cookie Store API 兼容性不足，标准做法是覆盖写入
  document.cookie = `${name}=; max-age=0; path=/`
}

export function getUserToken(): string | null {
  return localStorage.getItem(TOKEN_KEY)
}

export function getUserInfo<T = unknown>(): T | null {
  const raw = localStorage.getItem(USER_KEY)
  if (!raw) return null
  try {
    return JSON.parse(raw) as T
  } catch {
    return null
  }
}

export function isAuthed(): boolean {
  return getUserToken() !== null
}

export function setSession(token: string, userInfo: unknown) {
  localStorage.setItem(TOKEN_KEY, token)
  localStorage.setItem(USER_KEY, JSON.stringify(userInfo))
  window.dispatchEvent(new Event(AUTH_EVENT))
}

export function clearSession() {
  localStorage.removeItem(TOKEN_KEY)
  localStorage.removeItem(USER_KEY)
  window.dispatchEvent(new Event(AUTH_EVENT))
}
