import { useAuthStore } from "@/lib/api/auth-store"

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? "/api/v1"

export async function uploadFile(targetPath: string, file: File, onProgress?: (pct: number) => void) {
  const token = useAuthStore.getState().accessToken
  const path = targetPath.startsWith("/") ? targetPath : `/${targetPath}`
  const url = `${API_BASE}/drive/files${path}`

  const res = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
      "Content-Type": file.type || "application/octet-stream",
    },
    body: file,
  })
  if (!res.ok) {
    const err = await res.json().catch(() => ({}))
    throw new Error((err as { message?: string }).message ?? res.statusText)
  }
  onProgress?.(100)
}
