import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import type { BatchIdComboboxOption } from '@/components/shared/BatchIdCombobox';
import { fetchAllBatchIds } from '@/services/batchService';
import { queryKeys } from '@/lib/queryKeys';
import type { ProcurementBatch } from '@/types';

export function mapProcurementBatchesToOptions(batches: ProcurementBatch[]): BatchIdComboboxOption[] {
  return batches.map((batch) => ({
    value: batch.batch_id,
    label: batch.name ? `${batch.batch_id}（${batch.name}）` : batch.batch_id,
    searchText: batch.name ? `${batch.batch_id} ${batch.name}` : batch.batch_id,
  }));
}

export function useProcurementBatchOptions() {
  const { data: batches = [] } = useQuery({
    queryKey: queryKeys.procurement.batchOptions,
    queryFn: () => fetchAllBatchIds(),
  });

  const batchOptions = useMemo(() => mapProcurementBatchesToOptions(batches), [batches]);

  return {
    batches,
    batchOptions,
  };
}
