import { apiRequest } from './client';
import { FileType, Priority } from '~/types/enums';

/**
 * 将文件转换为二进制数据
 */
export async function uploadFileToBinary(file: File): Promise<ArrayBuffer> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      if (reader.result instanceof ArrayBuffer) {
        resolve(reader.result);
      } else {
        reject(new Error('文件读取失败'));
      }
    };
    reader.onerror = () => reject(new Error('文件读取失败'));
    reader.readAsArrayBuffer(file);
  });
}

/**
 * 上传文件到服务器
 */
export async function uploadFileToServer(
  binaryData: ArrayBuffer,
  fileName: string,
  fileType: string,
  documentType: FileType,
  priority: Priority
): Promise<{ success: boolean; fileId?: string; message?: string; error?: string }> {
  try {
    const formData = new FormData();
    formData.append('file', new Blob([binaryData], { type: fileType }), fileName);
    formData.append('documentType', documentType);
    formData.append('priority', priority);

    const response = await apiRequest<{ success: boolean; fileId?: string; message?: string }>(
      '/api/files/upload',
      {
        method: 'POST',
        body: formData
      }
    );

    if (response.error) {
      return { success: false, error: response.error };
    }

    return { success: true, fileId: response.data?.fileId, message: response.data?.message };
  } catch (error) {
    return { success: false, error: error instanceof Error ? error.message : '上传失败' };
  }
} 