import { useEffect } from 'react';
import { addToAnonRecentlyViewed } from './anonRecentlyViewedStore.js';
import { getCsrfToken } from '@/lib/csrf';

export function useTrackRecentlyViewed(dealId: string, isGuest: boolean): void {
  useEffect(() => {
    if (isGuest) {
      addToAnonRecentlyViewed(dealId);
      return;
    }
    void fetch('/api/me/recently-viewed', {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
        'x-csrf-token': getCsrfToken(),
      },
      body: JSON.stringify({ dealId }),
    });
  }, [dealId, isGuest]);
}
