import { request } from '@/api/request'

export interface PendingUpload {
  file_id: string
  object_key: string
  upload: {
    method: string
    url: string
    headers: Record<string, string>
    expires_at: string
  }
}

interface ApiResponse<T> {
  code: number
  message: string
  details: T
}

/** 初始化楼层布局文件并直传 OSS。 */
export async function uploadFloorLayout(file: File): Promise<PendingUpload> {
  const response = await request.post<ApiResponse<PendingUpload>>('/Assets/v1/floor/layout/init', {
    filename: file.name,
    size: file.size,
    content_type: file.type || 'application/octet-stream',
  })

  if (response.code !== 0) {
    throw new Error(response.message || '初始化楼层布局文件上传失败')
  }

  const pendingUpload = response.details
  if (!pendingUpload?.file_id || !pendingUpload.upload?.method || !pendingUpload.upload?.url) {
    throw new Error('楼层布局文件上传参数不完整')
  }

  const uploadResponse = await fetch(pendingUpload.upload.url, {
    method: pendingUpload.upload.method,
    headers: pendingUpload.upload.headers,
    body: file,
    credentials: 'omit',
  })
  if (!uploadResponse.ok) {
    throw new Error(`上传楼层布局文件失败: HTTP ${uploadResponse.status}`)
  }

  return pendingUpload
}
