import { type FC, type ReactNode } from 'react';
import { SWRConfig } from 'swr';

import type { Cache, SWRConfiguration } from 'swr';

import { setSwrCache } from './utils';

const swrConfig: SWRConfiguration = {
  // Don't retry — songwhipApi handles 401/403 redirects
  shouldRetryOnError: false,

  // Keep data fresh when switching tabs
  revalidateOnFocus: true,

  // Avoid request storms on reconnect
  revalidateOnReconnect: false,

  // Dedupe identical requests within 2s
  dedupingInterval: 2000,

  // Use a custom Map as the cache so revalidateByFetcher can directly
  // delete entries for unmounted hooks (SWR's `mutate` only reaches
  // currently-subscribed hooks and does not clear cache for others).
  provider: () => {
    const cache: Cache = new Map();
    setSwrCache(cache);
    return cache;
  },
};

export const SwrProvider: FC<{ children: ReactNode }> = ({ children }) => (
  <SWRConfig value={swrConfig}>{children}</SWRConfig>
);
