import { create } from 'zustand'
import { useEffect } from 'react'
import { useAllProducts } from '@/src/hooks/prominent-api-hooks'
import { AllProductsApiType } from '@backend/trpc/router'

type Product = AllProductsApiType['products'][number]

interface CentralProductState {
  products: Product[]
  productsById: Record<number, Product>
  refetchProducts: (() => Promise<void>) | null
  setProducts: (products: Product[]) => void
  clearProducts: () => void
  setRefetchProducts: (refetch: () => Promise<void>) => void
}

export const useCentralProductStore = create<CentralProductState>((set) => ({
  products: [],
  productsById: {},
  refetchProducts: null,
  setProducts: (products) => {
    const productsById: Record<number, Product> = {}

    products.forEach((product) => {
      productsById[product.id] = product
    })

    set({ products, productsById })
  },
  clearProducts: () => set({ products: [], productsById: {} }),
  setRefetchProducts: (refetchProducts) => set({ refetchProducts }),
}))

export function useInitializeCentralProductStore() {
  const { data: productsData, refetch } = useAllProducts()
  const setProducts = useCentralProductStore((state) => state.setProducts)
  const setRefetchProducts = useCentralProductStore((state) => state.setRefetchProducts)

  useEffect(() => {
    if (productsData?.products) {
      setProducts(productsData.products)
    }
  }, [productsData, setProducts])

  useEffect(() => {
    setRefetchProducts(async () => {
      await refetch()
    })
  }, [refetch, setRefetchProducts])
}
