import { useShallow } from 'zustand/shallow'
import type { Filters } from '@carto/api-client'
import { useSourceStore } from '../../providers/sources/store'

/**
 * Subscribes to the `useSourceStore` source and filter slices for the given
 * ids and returns them index-aligned with `sourcesId`. Used by per-model hook
 * wrappers (`useFormula`, `useCategories`, …) to feed a reactive store
 * snapshot into `createModel`'s imperative composition.
 *
 * The returned values are **consumed** downstream — they are projected into
 * each query key via `getModelQueryOptions`'s `sourceState` parameter, which
 * is what makes the hook re-derive its query key (and `useQuery` refetch) on
 * every `setSource(id, ...)` or filter mutation.
 *
 * Lives outside `create-model` because `babel-plugin-react-compiler` (used by
 * this package's build) elides hook calls whose return values are not
 * observably read; threading the slice through as data keeps the subscription
 * load-bearing.
 */
export function useSourceSlices(sourcesId: string[]) {
  const sources = useSourceStore(
    useShallow((state) => sourcesId.map((id) => state.sources[id])),
  )
  const filters = useSourceStore(
    useShallow(
      (state) =>
        sourcesId.map((id) => state.filters[id]) as (Filters | undefined)[],
    ),
  )

  return { sourcesId, sources, filters }
}
