import { buildDataProcessPreview } from '@/api/modules/dataProcess'
import type { DataProcessPreviewFileBuildProgress } from '@/types/dataProcess'

export function useDataProcessPreviewBuild() {
  async function buildPreviewsByFile(
    taskId: string | number,
    sourceFileIds: Array<string | number>,
    onProgress: (progress: DataProcessPreviewFileBuildProgress) => void,
  ) {
    const results: DataProcessPreviewFileBuildProgress[] = []
    for (const sourceFileId of sourceFileIds) {
      onProgress({ source_file_id: sourceFileId, status: 'processing', progress: 0 })
      let progress: DataProcessPreviewFileBuildProgress
      try {
        const built = await buildDataProcessPreview(taskId, {
          replace_existing: true,
          source_file_ids: [sourceFileId],
        })
        const sourceId = String(sourceFileId)
        const fileResult = built.files?.find((item) => String(item.source_file_id) === sourceId)
        const previewCount = fileResult?.preview_count
          ?? built.file_counts?.[sourceId]
          ?? built.items.filter((item) => String(item.source_file_id) === sourceId).length
        progress = previewCount > 0
          ? { source_file_id: sourceFileId, status: 'success', progress: 100, preview_count: previewCount }
          : {
              source_file_id: sourceFileId,
              status: 'failed',
              progress: 0,
              preview_count: 0,
              error: '该文件没有生成可用的预览条目，请检查内容或切分配置',
            }
      } catch (error) {
        progress = {
          source_file_id: sourceFileId,
          status: 'failed',
          progress: 0,
          error: error instanceof Error && error.message ? error.message : '切分失败，请重试',
        }
      }
      results.push(progress)
      onProgress(progress)
    }
    return results
  }

  return { buildPreviewsByFile }
}
