import { requestClient } from '#/api/request';

export namespace SystemStorageApi {
  /** 上传文件返回的 Blob 信息 */
  export interface StorageBlob {
    id: number; // 文件 ID
    resourceKey?: string; // 资源唯一标识
    contentType?: string; // MIME 类型
    originalFilename?: string; // 原文件名
    uidFilename?: string; // 唯一文件名
    byteSize?: number; // 文件大小（字节）
    path?: string; // 文件相对路径
    previewURL?: string; // 预览地址
    url?: string; // 文件访问 URL（兼容字段）
    name?: string; // 原文件名（兼容字段）
    downloadURL?: string; // 下载地址
    storageAttachmentId?: number; // 关联的附件 ID
    application?: string; // 文件用途
  }

  /** 附件绑定请求 */
  export interface AttachmentBindReq {
    application?: string; // 文件用途
    recordType: string; // 关联记录类型
    recordId: number; // 关联记录 ID
    blobItems: { blobId: number; application?: string }[]; // 待绑定的文件列表
  }

  /** 附件列表查询参数 */
  export interface AttachmentListParams {
    recordType: string;
    recordId: number;
    application?: string;
  }
}

/** 上传文件 */
export function uploadFile(files: globalThis.File[]) {
  const formData = new FormData();
  files.forEach((file) => formData.append('files', file));
  return requestClient.post<SystemStorageApi.StorageBlob[]>(
    '/system/storage-blob/upload',
    formData,
    { headers: { 'Content-Type': 'multipart/form-data' } },
  );
}

/** 查询附件列表 */
export function listAttachments(params: SystemStorageApi.AttachmentListParams) {
  return requestClient.get<SystemStorageApi.StorageBlob[]>(
    '/system/storage-attachment/list',
    { params },
  );
}

/** 绑定附件到业务记录 */
export function bindAttachments(data: SystemStorageApi.AttachmentBindReq) {
  return requestClient.post<boolean>(
    '/system/storage-attachment/bind',
    data,
  );
}

/** 批量删除附件 */
export function deleteAttachments(ids: number[]) {
  return requestClient.delete<boolean>('/system/storage-attachment/delete', {
    data: ids,
  });
}
