import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { isJwtExpired } from '@/utils/jwt'
import { useAuthStore } from '@/stores/auth'

export type UploadProgressHandler = (percent: number) => void

const fileClient = axios.create({
  baseURL: import.meta.env.VITE_FILE_SERVICE_URL ?? '',
  timeout: 600000, // 10分钟，支持大文件在慢网速下上传
})

if (import.meta.env.DEV) {
  fileClient.interceptors.request.use((config) => {
    console.debug('[tenant-platform][FILE] request', {
      method: config.method?.toUpperCase(),
      url: config.baseURL ? `${config.baseURL}${config.url ?? ''}` : config.url,
      params: config.params,
    })
    return config
  })
  fileClient.interceptors.response.use((res) => {
    console.debug('[tenant-platform][FILE] response', {
      status: res.status,
      url: res.config.url,
    })
    return res
  })
}

fileClient.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token && !isJwtExpired(token)) {
    config.headers.Authorization = `Bearer ${token}`
  } else if (token && isJwtExpired(token)) {
    useAuthStore().logout()
    if (router.currentRoute.value.path !== '/login') {
      router.push('/login?reason=' + encodeURIComponent('登录已失效，请重新登录'))
    }
    return Promise.reject(new Error('登录已失效，请重新登录'))
  }
  return config
})

fileClient.interceptors.response.use(
  (res) => res,
  (error) => {
    const status = error.response?.status
    if (status === 401) {
      useAuthStore().logout()
      if (router.currentRoute.value.path !== '/login') {
        router.push('/login')
      }
      ElMessage.error('登录已失效，请重新登录')
      return Promise.reject(error)
    }
    if (status === 403) {
      ElMessage.error(error.response?.data?.message ?? '无权限执行此操作')
      return Promise.reject(error)
    }
    const msg = error.response?.data?.message ?? '文件请求失败'
    ElMessage.error(msg)
    return Promise.reject(error)
  },
)

export interface FileUploadResult {
  url: string
  thumbnailUrl?: string
  hash: string
  size: number
  originalName: string
  mimeType?: string
  ext?: string
}

export const fileApi = {
  uploadFile(file: File, thumbnail?: File | null, onProgress?: UploadProgressHandler) {
    const formData = new FormData()
    formData.append('file', file)
    if (thumbnail) {
      formData.append('thumbnail', thumbnail)
    }
    return fileClient.post<{ data: FileUploadResult }>('/api/file/upload', formData, {
      onUploadProgress: (event) => {
        if (!onProgress) return
        const total = event.total ?? 0
        if (!total) return
        onProgress(Math.min(100, Math.round((event.loaded * 100) / total)))
      },
    })
  },
}
