import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import client from '../api/client'
import db from '../db/posdb'

export const PRODUCTS_KEY = ['products']

async function fetchAndCacheProducts() {
  const [prodRes, catRes] = await Promise.all([
    client.get('/api/products/'),
    client.get('/api/products/categories'),
  ])
  const products = prodRes.data
  const categories = catRes.data

  db.products.bulkPut(products).catch(() => {})
  db.categories.bulkPut(categories).catch(() => {})

  return { products, categories }
}

async function loadFromCache() {
  const [products, categories] = await Promise.all([
    db.products.toArray(),
    db.categories.toArray(),
  ])
  if (products.length === 0 && categories.length === 0) return null
  return { products, categories }
}

export function useProductCache() {
  const queryClient = useQueryClient()
  const [idbData, setIdbData] = useState(null)
  const [idbLoaded, setIdbLoaded] = useState(false)

  // Load IDB data immediately on mount — this is the offline fallback
  useEffect(() => {
    loadFromCache().then(data => {
      setIdbData(data)
      setIdbLoaded(true)
      // Seed the query cache so React Query uses it as starting data
      if (data && !queryClient.getQueryData(PRODUCTS_KEY)) {
        queryClient.setQueryData(PRODUCTS_KEY, data)
      }
    })
  }, [queryClient])

  const query = useQuery({
    queryKey: PRODUCTS_KEY,
    queryFn: fetchAndCacheProducts,
    staleTime: 5 * 60 * 1000,
    gcTime: 60 * 60 * 1000,
    // Don't retry on failure — axios interceptor already fired backend-offline
    // which switches connection state; we fall back to IDB data instead
    retry: false,
    // Only start the query after we've checked IDB, so IDB data is visible first
    enabled: idbLoaded,
  })

  // Prefer live query data; fall back to IDB snapshot if query failed or is loading
  const data = query.data ?? idbData

  return {
    products:   data?.products   ?? [],
    categories: data?.categories ?? [],
    isLoading:  !idbLoaded && query.isLoading,
  }
}

export function invalidateProductCache(queryClient) {
  queryClient.invalidateQueries({ queryKey: PRODUCTS_KEY })
}
