import { System } from '@/lib/types';
import { useQuery } from '@tanstack/react-query';

const pocketbaseUrl = `https://evebase.site.quack-lab.dev/api/collections/regionview/records`;

const fetchRegionData = async (regionName: string): Promise<Map<string, System>> => {
  const response = await fetch(`/${regionName}.json`);
  if (!response.ok) {
    throw new Error('Failed to fetch region data');
  }
  const systems = await response.json();
  const systemsMap = new Map<string, System>();
  systems.forEach(system => {
    systemsMap.set(system.solarSystemName, system);
  });

  const regionSignatures = await fetch(`${pocketbaseUrl}?filter=(sysregion%3D'${regionName}')&perPage=1000`);
  const regionSignaturesJson = await regionSignatures.json();
  if (regionSignaturesJson.items.length > 0) {
    for (const systemSigs of regionSignaturesJson.items) {
      const system = systemsMap.get(systemSigs.sysname);
      if (system)
        system.signatures = systemSigs.sigcount;
    }
  }
  return systemsMap;
};

export const useRegionData = (regionName: string) => {
  return useQuery({
    queryKey: ['region', regionName],
    queryFn: () => fetchRegionData(regionName),
  });
};
