import { useEffect } from 'react'
import { useVersionStore } from '../stores/version-store'
import { AppType } from '@/infrastructure'

export function useVersions() {
  const {
    versions,
    isLoading,
    error,
    filter,
    appType,
    fetchVersions,
    setFilter,
    setAppType,
    clearError,
  } = useVersionStore()

  useEffect(() => {
    fetchVersions()
  }, [filter.platform, filter.includeDisabled, appType])

  return {
    versions,
    isLoading,
    error,
    filter,
    appType,
    refetch: fetchVersions,
    setFilter,
    setAppType,
    clearError,
  }
}

export function useVersion(id: string | null) {
  const {
    selectedVersion,
    isLoading,
    error,
    fetchVersionById,
    setSelectedVersion,
    clearError,
  } = useVersionStore()

  useEffect(() => {
    if (id) {
      fetchVersionById(id)
    } else {
      setSelectedVersion(null)
    }
  }, [id])

  return {
    version: selectedVersion,
    isLoading,
    error,
    refetch: () => id && fetchVersionById(id),
    clearError,
  }
}

export function useVersionActions() {
  const {
    fetchVersions,
    setFilter,
    setAppType,
    appType,
    createVersion,
    updateVersion,
    deleteVersion,
    toggleVersion,
    uploadVersion,
    isLoading,
    error,
    clearError,
  } = useVersionStore()

  return {
    loadVersions: fetchVersions,
    setFilter,
    setAppType,
    appType,
    createVersion,
    updateVersion,
    deleteVersion,
    toggleVersion,
    uploadVersion,
    isLoading,
    error,
    clearError,
  }
}

export function useAppType() {
  const { appType, setAppType } = useVersionStore()
  return { appType, setAppType }
}
