import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import { trpc } from '@/src/trpc-client'
import { AllProductsApiType, StoresApiType, SlotsApiType, EssentialConstsApiType, BannersApiType, StoreWithProductsApiType } from "@backend/trpc/router";
import { CACHE_FILENAMES } from "@packages/shared";

// Local useGetEssentialConsts hook
export const useGetEssentialConsts = () => {
  const query = trpc.common.essentialConsts.useQuery(undefined, {
    refetchInterval: 60000,
  })
  return { ...query, refetch: query.refetch }
}

type ProductsResponse = AllProductsApiType;
type StoresResponse = StoresApiType;
type SlotsResponse = SlotsApiType;
type EssentialConstsResponse = EssentialConstsApiType;
type BannersResponse = BannersApiType;
type StoreWithProductsResponse = StoreWithProductsApiType;

function useCacheUrl(filename: string): string | null {
  const { data: essentialConsts } = useGetEssentialConsts()

  const assetsDomain = essentialConsts?.assetsDomain
  const apiCacheKey = essentialConsts?.apiCacheKey
  const cacheVersion = essentialConsts?.cacheVersion

  if (!assetsDomain || !apiCacheKey || cacheVersion === undefined || cacheVersion === null) {
    return null
  }

  return `${assetsDomain}${apiCacheKey}/v-${cacheVersion}/${filename}`
}

export function useAllProducts() {
  const cacheUrl = useCacheUrl(CACHE_FILENAMES.products)

  
  return useQuery<ProductsResponse>({
    queryKey: ['all-products', cacheUrl],
    queryFn: async () => {
      if (!cacheUrl) {
        throw new Error('Cache URL not available')
      }
      const response = await axios.get<ProductsResponse>(cacheUrl)
      return response.data
    },
    staleTime: 60000, // 1 minute
    enabled: !!cacheUrl,
  })
}

export function useStores() {
  const cacheUrl = useCacheUrl(CACHE_FILENAMES.stores)

  return useQuery<StoresResponse>({
    queryKey: ['stores', cacheUrl],
    queryFn: async () => {
      if (!cacheUrl) {
        throw new Error('Cache URL not available')
      }
      const response = await axios.get<StoresResponse>(cacheUrl)
      return response.data
    },
    staleTime: 60000, // 1 minute
    enabled: !!cacheUrl,
  })
}

export function useSlots() {
  const cacheUrl = useCacheUrl(CACHE_FILENAMES.slots)

  return useQuery<SlotsResponse>({
    queryKey: ['slots', cacheUrl],
    queryFn: async () => {
      if (!cacheUrl) {
        throw new Error('Cache URL not available')
      }
      const response = await axios.get<SlotsResponse>(cacheUrl+'?v=123')
      return response.data
    },
    staleTime: 60000, // 1 minute
    enabled: !!cacheUrl,
  })
}

export function useBanners() {
  const cacheUrl = useCacheUrl(CACHE_FILENAMES.banners)

  return useQuery<BannersResponse>({
    queryKey: ['banners', cacheUrl],
    queryFn: async () => {
    
        if (!cacheUrl) {
          throw new Error('Cache URL not available')
        }
        const response = await axios.get<BannersResponse>(cacheUrl)
        return response.data
      
    },
    staleTime: 60000, // 1 minute
    enabled: !!cacheUrl,
  })
}

export function useStoreWithProducts(storeId: number) {
  const { data: essentialConsts } = useGetEssentialConsts()

  const assetsDomain = essentialConsts?.assetsDomain
  const apiCacheKey = essentialConsts?.apiCacheKey
  const cacheVersion = essentialConsts?.cacheVersion;

  const cacheUrl = assetsDomain && apiCacheKey
    ? `${assetsDomain}${apiCacheKey}/v-${cacheVersion}/stores/${storeId}.json`
    : null

  return useQuery<StoreWithProductsResponse>({
    queryKey: ['store-with-products', storeId, cacheUrl],
    queryFn: async () => {
      if (!cacheUrl) {
        throw new Error('Cache URL not available')
      }
      const response = await axios.get<StoreWithProductsResponse>(cacheUrl)
      return response.data
    },
    staleTime: 60000, // 1 minute
    enabled: !!cacheUrl,
  })
}
