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

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

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

  return {
    versions,
    isLoading,
    error,
    filter,
    refetch: fetchVersions,
    setFilter,
    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,
    createVersion,
    updateVersion,
    deleteVersion,
    toggleVersion,
    uploadVersion,
    isLoading,
    error,
    clearError,
  } = useVersionStore()

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