const TOKEN_KEY = 'token'

/**
 * 获取 cookie 值
 */
function getCookie(name: string): string | null {
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'))
  return match ? decodeURIComponent(match[2]) : null
}

/**
 * 设置 cookie
 * @param name cookie 名称
 * @param value cookie 值
 * @param expiresIn 过期时间（秒），默认 1 天
 */
function setCookie(name: string, value: string, expiresIn: number = 86400): void {
  const expires = new Date(Date.now() + expiresIn * 1000).toUTCString()
  document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/; SameSite=Lax`
}

/**
 * 删除 cookie
 */
function removeCookie(name: string): void {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
}

export function getToken(): string | null {
  return getCookie(TOKEN_KEY)
}

export function setToken(token: string, expiresIn: number = 86400): void {
  setCookie(TOKEN_KEY, token, expiresIn)
}

export function removeToken(): void {
  removeCookie(TOKEN_KEY)
}
