import type { QueryClient } from '@tanstack/react-query' import type { RegionSummary } from '@packages/shared' import { clearLocalCart } from '@/hooks/cart-query-hooks' import { useRegionStore } from '@/src/store/regionStore' import { useCartStore } from '@/src/store/cartStore' import { useFlashCartStore } from '@/src/store/flashCartStore' import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore' import { useAddressStore } from '@/src/store/addressStore' import { useCentralProductStore } from '@/src/store/centralProductStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useSlotStore } from '@/components/stores/slotStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' /** * The one and only way to change the browsing region. * * Manual switching (RegionSelector) and the checkout address flow both call * this so the reset behaviour can never drift. It clears every cart variant, * drops derived checkout selections, persists the new region and invalidates * region-scoped react-query caches. * * NOTE: callers must obtain a user confirmation before invoking this. */ export async function confirmRegionSwitch( region: RegionSummary, queryClient: QueryClient, boundId?: number | null, ): Promise { // 1. Clear the persisted local carts (regular + flash). await Promise.all([clearLocalCart('regular'), clearLocalCart('flash')]) // 2. Drop in-memory checkout / quick-delivery selections. useQuickDeliveryStore.getState().setSelectedSlotId(null) useAddressStore.getState().setSelectedAddressId(null) useSlotStore.getState().setSlotId(undefined) useSlotStore.getState().setStoreId(undefined) useCartStore.getState().clearAddedToCartProduct() useFlashCartStore.getState().clearAddedFlashProduct() useFlashNavigationStore.getState().reset() // 3. Drop cached regional catalog/slot snapshots so they cannot leak across. const productStore = useCentralProductStore.getState() productStore.setProducts([]) productStore.setRefetchProducts(null) useCentralSlotStore.getState().setSlotsData([], [], []) // Drop the old region's versioned catalog queries so no stale cross-region // products/prices/tags survive; the invalidate below refetches discovery + // catalog files for the new region. queryClient.removeQueries({ queryKey: ['all-products'] }) queryClient.removeQueries({ queryKey: ['stores'] }) queryClient.removeQueries({ queryKey: ['slots'] }) queryClient.removeQueries({ queryKey: ['availability'] }) queryClient.removeQueries({ queryKey: ['store-with-products'] }) // 4. Persist the new browsing region (and its bound). useRegionStore.getState().setRegion(region, boundId ?? region.effectiveBoundId ?? null) // 5. Refetch everything now scoped to the new region. await queryClient.invalidateQueries() }