import axios from 'axios'
import request from '@/utils/http'
import { useUserStore } from '@/store/modules/user'

export interface FileObject {
  id: string
  original_name: string
  content_type: string
  size_bytes: number
  content_sha256: string
  scope: string
  owner_user_id?: string
  created_by: string
  created_at: string
  updated_at: string
}

export const fetchFiles = () => request.get<FileObject[]>({ url: '/api/v1/admin/files' })
export const uploadFile = (file: File) => {
  const form = new FormData()
  form.append('file', file)
  return request.post<FileObject>({ url: '/api/v1/admin/files', data: form, timeout: 120000 })
}
export const deleteFile = (id: string) => request.del({ url: `/api/v1/admin/files/${id}` })

// 文件体以 blob 流式下载，绕开统一响应拦截器（其期望 JSON envelope）。
export async function downloadFile(id: string, filename: string) {
  const { accessToken } = useUserStore()
  const token = accessToken.startsWith('Bearer ') ? accessToken : `Bearer ${accessToken}`
  const res = await axios.get(`/api/v1/admin/files/${id}/download`, {
    baseURL: import.meta.env.VITE_API_URL,
    headers: { Authorization: token },
    responseType: 'blob'
  })
  const url = URL.createObjectURL(res.data)
  const anchor = document.createElement('a')
  anchor.href = url
  anchor.download = filename
  anchor.click()
  URL.revokeObjectURL(url)
}
