/**
 * Cookie 工具类
 * 用于管理用户信息的存储和读取
 */

// 用户信息类型
export interface UserInfo {
  id: number
  username: string
  email: string
  avatar_url?: string
}

// 设置cookie
export const setCookie = (name: string, value: string, days: number = 7): void => {
  const expires = new Date()
  expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000)

  const cookieOptions = [
    `${name}=${value}`,
    `expires=${expires.toUTCString()}`,
    'path=/',
    'SameSite=Lax'
  ]

  // 在生产环境下添加 Secure 标志
  if (window.location.protocol === 'https:') {
    cookieOptions.push('Secure')
  }

  document.cookie = cookieOptions.join('; ')
}

// 获取cookie值
export const getCookie = (name: string): string | null => {
  const nameEQ = name + '='
  const cookies = document.cookie.split(';')

  for (let cookie of cookies) {
    cookie = cookie.trim()
    if (cookie.indexOf(nameEQ) === 0) {
      return cookie.substring(nameEQ.length)
    }
  }

  return null
}

// 删除cookie
export const deleteCookie = (name: string): void => {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`
}

// 存储用户信息到cookie
export const setUserInfoInCookie = (userInfo: UserInfo): void => {
  const userInfoString = JSON.stringify(userInfo)
  setCookie('userInfo', userInfoString, 7) // 7天过期
}

// 从cookie获取用户信息
export const getUserInfoFromCookie = (): UserInfo | null => {
  const userInfoString = getCookie('userInfo')
  if (!userInfoString) return null

  try {
    return JSON.parse(userInfoString)
  } catch (error) {
    console.error('解析用户信息失败:', error)
    deleteCookie('userInfo') // 清除无效的cookie
    return null
  }
}

// 存储JWT token到cookie
export const setTokenInCookie = (token: string): void => {
  setCookie('token', token, 7) // 7天过期
}

// 从cookie获取JWT token
export const getTokenFromCookie = (): string | null => {
  return getCookie('token')
}

// 获取用户ID
export const getUserIdFromCookie = (): number | null => {
  const userInfo = getUserInfoFromCookie()
  return userInfo?.id || null
}

// 清除所有认证相关的cookie
export const clearAuthCookies = (): void => {
  deleteCookie('userInfo')
  deleteCookie('token')
}