import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { FileInfo } from '@/types/api'

interface UploadState {
  batchId: number | null
  files: FileInfo[]
  uploadProgress: number
  setBatchId: (id: number) => void
  setFiles: (files: FileInfo[]) => void
  setUploadProgress: (progress: number) => void
  updateFileStatus: (fileId: number, status: FileInfo['status']) => void
  clearUpload: () => void
}

/**
 * Upload Store
 * Manages file upload state with localStorage persistence
 */
export const useUploadStore = create<UploadState>()(
  persist(
    (set) => ({
      batchId: null,
      files: [],
      uploadProgress: 0,
      setBatchId: (id) => {
        set({ batchId: id })
      },
      setFiles: (files) => set({ files }),
      setUploadProgress: (progress) => set({ uploadProgress: progress }),
      updateFileStatus: (fileId, status) =>
        set((state) => ({
          files: state.files.map((file) =>
            file.id === fileId ? { ...file, status } : file
          ),
        })),
      clearUpload: () =>
        set({
          batchId: null,
          files: [],
          uploadProgress: 0,
        }),
    }),
    {
      name: 'tool-ocr-upload-store',
      // Only persist batchId and files, not upload progress
      partialize: (state) => ({
        batchId: state.batchId,
        files: state.files,
      }),
    }
  )
)
