import { create } from 'zustand'
import axiosInstance from '@/utils/axios'
import { IExport, type SearchExportsParams } from '@/shared/types/export'

type ExportServiceKey =
  | 'user-service'
  | 'circuit-service'
  | 'fleet-service'
  | 'hr-service'
  | 'admin-service'
  | 'roadsheet-service'
  | 'planning-service'
  | 'document-service'

type ExportStore = {
  items: IExport[]
  totalElements: number
  loading: boolean
  error: string | null
  fetchExports: (service: ExportServiceKey, params?: SearchExportsParams) => Promise<void>
  downloadExport: (service: ExportServiceKey, filePath: string) => Promise<void>
}

const LIST_ENDPOINTS: Record<ExportServiceKey, string> = {
  'user-service': '/api/user/exportList',
  'circuit-service': '/api/circuit/exportList',
  'fleet-service': '/api/fleet/exportList',
  'hr-service': '/api/hr/exportList',
  'admin-service': '/api/admin/exportList',
  'roadsheet-service': '/api/roadsheet/exportList',
  'planning-service': '/api/planning/exportList',
  'document-service': '/api/document/exportList',
}

const DOWNLOAD_ENDPOINTS: Record<ExportServiceKey, string> = {
  'user-service': '/api/user/driver/export/download',
  'circuit-service': '/api/circuit/export/download',
  'fleet-service': '/api/fleet/export/download',
  'hr-service': '/api/hr/export/download',
  'admin-service': '/api/admin/contracts/download-export',
  'roadsheet-service': '/api/roadsheet/export/download',
  'planning-service': '/api/planning/export/download',
  'document-service': '/api/document/export/download',
}

export const useExportStore = create<ExportStore>((set) => ({
  items: [],
  totalElements: 0,
  loading: false,
  error: null,

  fetchExports: async (service, params = {}) => {
    set({ loading: true, error: null })
    try {
      const endpoint = LIST_ENDPOINTS[service]
      if (!endpoint) throw new Error('Service de liste non supporté')

      const response = await axiosInstance.get(endpoint, { params })

      const content: IExport[] = response.data?.content ?? response.data ?? []
      const total: number = response.data?.totalElements ?? content.length

      set({ items: content, totalElements: total, loading: false })
    } catch (error: any) {
      set({ items: [], totalElements: 0, error: error?.message || 'Erreur lors du chargement des exports', loading: false })
    }
  },

  downloadExport: async (service, filePath) => {
    try {
      const endpoint = DOWNLOAD_ENDPOINTS[service]
      if (!endpoint) throw new Error('Service de téléchargement non supporté')

      const response = await axiosInstance.get(endpoint, {
        params: { filePath },
        responseType: 'blob',
      })

      const blob = new Blob([response.data], { type: 'text/csv;charset=utf-8;' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      const filename = String(filePath || '').split(/[\\/]/).pop() || 'export.csv'
      link.setAttribute('download', filename)
      document.body.appendChild(link)
      link.click()
      link.parentNode?.removeChild(link)
      window.URL.revokeObjectURL(url)

      // Mettre à jour le statut de téléchargement dans la liste
      set((state) => ({
        items: state.items.map((item) =>
          item.filePath === filePath
            ? {
                ...item,
                downloaded: true,
                downloadDate: new Date().toISOString(),
              }
            : item
        ),
      }))
    } catch (error) {
      // On garde silencieux ici; le composant appelant peut notifier si besoin
    }
  },
}))


