import { useQuery } from '@tanstack/react-query'; import { useMemo } from 'react'; import { BackendSite } from '@/schemas/backend/site'; import { getAllSites } from '@/services/sites-api'; import { Organization } from '@/types'; /** * Hook to fetch sites for multiple organizations * Returns a map of organization ID -> site (first site if multiple) */ export const useOrganizationSites = (organizations: Organization[]) => { // Filter out organizations without valid IDs const validOrgs = useMemo( () => organizations.filter((org) => org.ID && org.ID.trim() !== ''), [organizations] ); const { data: allSites = [], isLoading, error } = useQuery({ queryKey: ['sites', 'all'], queryFn: getAllSites, staleTime: 5 * 60 * 1000, // 5 minutes gcTime: 10 * 60 * 1000, // 10 minutes retry: 1, retryDelay: 1000, }); // Debug logging for sites query if (process.env.NODE_ENV === 'development') { if (error) { console.error('[useOrganizationSites] Sites query error:', error); } } // Create a map of org ID -> first site (or null) const orgSitesMap = useMemo(() => { const map = new Map(); validOrgs.forEach((org) => { // Find sites that belong to this organization const orgSites = allSites.filter((site) => site.OwnerOrganizationID === org.ID); if (orgSites.length > 0) { // Use first site if multiple exist map.set(org.ID, orgSites[0]); } else { map.set(org.ID, null); } }); // Debug logging if (process.env.NODE_ENV === 'development') { console.log('[useOrganizationSites]', { totalOrgs: validOrgs.length, totalSites: allSites.length, sitesWithOwners: allSites.filter(s => s.OwnerOrganizationID !== 'unknown-org').length, orgSitesMapSize: map.size, sampleMappings: Array.from(map.entries()).slice(0, 5).map(([orgId, site]) => ({ orgId, hasSite: !!site, siteCoords: site ? [site.Latitude, site.Longitude] : null, })), }); } return map; }, [validOrgs, allSites]); return { orgSitesMap, isLoading, }; };