import { useEffect, useMemo, useCallback } from 'react';
import { useArticles } from './useArticles.js';
import { useStorageLocations } from './useStorageLocations.js';

export function useStockNameLookup() {
  const { articles, fetchArticles } = useArticles();
  const { storageLocations, fetchStorageLocations } = useStorageLocations();

  useEffect(() => {
    void fetchArticles();
    void fetchStorageLocations();
  }, [fetchArticles, fetchStorageLocations]);

  const articleNames = useMemo(() => {
    const map = new Map<string, string>();
    for (const a of articles) map.set(a.id, a.name);
    return map;
  }, [articles]);

  const locationNames = useMemo(() => {
    const map = new Map<string, string>();
    for (const l of storageLocations) map.set(l.id, l.name);
    return map;
  }, [storageLocations]);

  const articleName = useCallback(
    (id: string) => articleNames.get(id) ?? id.substring(0, 8) + '…',
    [articleNames],
  );

  const locationName = useCallback(
    (id: string) => locationNames.get(id) ?? id.substring(0, 8) + '…',
    [locationNames],
  );

  return { articleName, locationName };
}
