import api from '../utils/request'

export interface ClientDistribution {
  id: number
  name: string
  description?: string
  icon_url?: string
  icon_object_key?: string
  owner_id: number
  created_at: string
  updated_at?: string
  /** 由 id+created_at 生成的固定无规律分享标识，用于 /d/{share_id} */
  share_id: string
}

export interface ClientVersion {
  id: number
  distribution_id: number
  version_code: string
  version_name?: string
  release_notes?: string
  object_key: string
  file_size?: number
  platform?: string
  created_at: string
}

export interface DistributionListResponse {
  total: number
  items: ClientDistribution[]
}

export interface VersionListResponse {
  total: number
  items: ClientVersion[]
}

export interface LatestVersionInfoPublic {
  id: number
  version_code: string
  version_name?: string
  release_notes?: string
  file_size?: number
  platform?: string
  created_at: string
  download_url: string
}

export interface DistributionPublicResponse {
  id: number
  name: string
  description?: string
  icon_url?: string
  latest_version?: LatestVersionInfoPublic
  /** 按平台分组的最新版本，key 为 platform 枚举值 */
  latest_versions_by_platform?: Record<string, LatestVersionInfoPublic>
}

export const listDistributions = (params?: { skip?: number; limit?: number; search?: string }) => {
  return api.get<DistributionListResponse>('/client-distributions/', { params })
}

export const createDistribution = (data: { name: string; description?: string; icon_url?: string }) => {
  return api.post<ClientDistribution>('/client-distributions/', data)
}

export const getDistribution = (id: number) => {
  return api.get<ClientDistribution>(`/client-distributions/${id}`)
}

export const updateDistribution = (id: number, data: Partial<{ name: string; description: string; icon_url: string }>) => {
  return api.put<ClientDistribution>(`/client-distributions/${id}`, data)
}

export const deleteDistribution = (id: number) => {
  return api.delete(`/client-distributions/${id}`)
}

/** 上传分发图标，distributionId=0 表示创建时，>0 表示编辑时 */
export const uploadDistributionIcon = (file: File, distributionId: number = 0) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('distribution_id', String(distributionId))
  return api.post<{ object_key: string }>('/client-distributions/icon/upload', formData)
}

export const listVersions = (
  distId: number,
  params?: { skip?: number; limit?: number; platform?: string; search?: string }
) => {
  return api.get<VersionListResponse>(`/client-distributions/${distId}/versions`, { params })
}

export const createVersion = (
  distId: number,
  formData: FormData,
  options?: { onUploadProgress?: (percent: number) => void }
) => {
  return api.post<ClientVersion>(`/client-distributions/${distId}/versions`, formData, {
    timeout: 300000,
    onUploadProgress: options?.onUploadProgress
      ? (e) => {
          const percent = e.total ? Math.round((e.loaded / e.total) * 100) : 0
          options.onUploadProgress!(percent)
        }
      : undefined
  })
}

export const updateVersion = (versionId: number, data: Partial<{ version_name: string; release_notes: string; platform: string }>) => {
  return api.put<ClientVersion>(`/client-distributions/versions/${versionId}`, data)
}

export const deleteVersion = (versionId: number) => {
  return api.delete(`/client-distributions/versions/${versionId}`)
}

// 公开接口，无需 token；shareId 为分享链接中的无规律 id。404 时由页面自行处理，不触发全局错误提示
export const getDistributionPublic = (shareId: string) => {
  return api.get<DistributionPublicResponse>(`/open/distribution/${shareId}`, {
    skipGlobalErrorHandler: true
  })
}

// 自建更新文件（update 桶，路径：创建时间戳/平台/update/...）
export interface UpdateFileItem {
  key: string
  name: string
  size: number
  url: string
}

export interface UpdateFilesResponse {
  base_url: string
  files: UpdateFileItem[]
}

export const listUpdateFiles = (distId: number, platform: string) => {
  return api.get<UpdateFilesResponse>(`/client-distributions/${distId}/update-files`, {
    params: { platform }
  })
}

export const uploadUpdateFile = (
  distId: number,
  platform: string,
  file: File,
  options?: { onUploadProgress?: (percent: number) => void }
) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('platform', platform)
  return api.post<{ object_key: string; url: string }>(
    `/client-distributions/${distId}/update-files`,
    formData,
    {
      timeout: 300000,
      onUploadProgress: options?.onUploadProgress
        ? (e) => {
            const percent = e.total ? Math.round((e.loaded / e.total) * 100) : 0
            options.onUploadProgress!(percent)
          }
        : undefined
    }
  )
}

export const deleteUpdateFile = (distId: number, platform: string, key: string) => {
  return api.delete(`/client-distributions/${distId}/update-files`, {
    params: { platform, key }
  })
}
