import axios from 'axios'
import { tokenManager } from './client'
import type { AuthResponse, LoginRequest, RegisterRequest } from '@/types'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api'

// 生成设备指纹
function generateDeviceFingerprint(): string {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  if (ctx) {
    ctx.textBaseline = 'top'
    ctx.font = '14px Arial'
    ctx.fillText('fingerprint', 2, 2)
  }
  const canvasFingerprint = canvas.toDataURL()

  const screenFingerprint = `${screen.width}x${screen.height}x${screen.colorDepth}`
  const timezoneFingerprint = Intl.DateTimeFormat().resolvedOptions().timeZone
  const languageFingerprint = navigator.language

  const combined = `${canvasFingerprint}-${screenFingerprint}-${timezoneFingerprint}-${languageFingerprint}`

  // 简单哈希
  let hash = 0
  for (let i = 0; i < combined.length; i++) {
    const char = combined.charCodeAt(i)
    hash = ((hash << 5) - hash) + char
    hash = hash & hash
  }
  return Math.abs(hash).toString(16)
}

// 获取设备类型
function getDeviceType(): string {
  const ua = navigator.userAgent
  let browser = 'Unknown'
  let os = 'Unknown'

  // 检测浏览器
  if (ua.includes('Chrome') && !ua.includes('Edg')) {
    browser = 'Chrome'
  } else if (ua.includes('Edg')) {
    browser = 'Edge'
  } else if (ua.includes('Firefox')) {
    browser = 'Firefox'
  } else if (ua.includes('Safari') && !ua.includes('Chrome')) {
    browser = 'Safari'
  }

  // 检测操作系统
  if (ua.includes('Windows')) {
    os = 'Windows'
  } else if (ua.includes('Mac')) {
    os = 'macOS'
  } else if (ua.includes('Linux')) {
    os = 'Linux'
  } else if (ua.includes('Android')) {
    os = 'Android'
  } else if (ua.includes('iOS') || ua.includes('iPhone') || ua.includes('iPad')) {
    os = 'iOS'
  }

  return `${browser} on ${os}`
}

// 获取设备名称
function getDeviceName(): string {
  const deviceType = getDeviceType()
  const date = new Date().toLocaleDateString('zh-CN')
  return `${deviceType} - ${date}`
}

export const authApi = {
  /**
   * 用户注册
   */
  async register(data: RegisterRequest): Promise<AuthResponse> {
    const response = await axios.post<AuthResponse>(`${API_BASE_URL}/auth/register`, data)
    return response.data
  },

  /**
   * 用户登录
   */
  async login(email: string, password: string): Promise<AuthResponse> {
    const loginData: LoginRequest = {
      email,
      password,
      deviceName: getDeviceName(),
      deviceType: getDeviceType(),
      deviceFingerprint: generateDeviceFingerprint()
    }

    const response = await axios.post<AuthResponse>(`${API_BASE_URL}/auth/login`, loginData)

    if (response.data.success && response.data.accessToken) {
      tokenManager.setAccessToken(response.data.accessToken)
      tokenManager.setRefreshToken(response.data.refreshToken!)
      tokenManager.setTokenExpires(response.data.expiresAt!)
    }

    return response.data
  },

  /**
   * 退出登录
   */
  async logout(): Promise<void> {
    try {
      const token = tokenManager.getAccessToken()
      if (token) {
        await axios.post(
          `${API_BASE_URL}/auth/logout`,
          {},
          { headers: { Authorization: `Bearer ${token}` } }
        )
      }
    } finally {
      tokenManager.clearTokens()
    }
  },

  /**
   * 刷新令牌
   */
  async refreshToken(): Promise<AuthResponse> {
    const refreshToken = tokenManager.getRefreshToken()
    if (!refreshToken) {
      throw new Error('No refresh token')
    }

    const response = await axios.post<AuthResponse>(`${API_BASE_URL}/auth/refresh`, {
      refreshToken
    })

    if (response.data.success && response.data.accessToken) {
      tokenManager.setAccessToken(response.data.accessToken)
      tokenManager.setRefreshToken(response.data.refreshToken!)
      tokenManager.setTokenExpires(response.data.expiresAt!)
    }

    return response.data
  }
}

