/**
 * useFieldOptions Hook
 *
 * Manages fetching and caching of field options from the API.
 * Options are used to populate select dropdowns in the validation table.
 */

import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '@/utils/api';
import config from '@/config';
import type { SelectOption } from '../../../types';

export interface FieldOptionsResponse {
  suppliers: SelectOption[];
  companies: SelectOption[];
  taxCategories: SelectOption[];
  artists: SelectOption[];
  shippingRestrictions: SelectOption[];  // API returns 'shippingRestrictions'
  sizes: SelectOption[];  // API returns 'sizes'
  categories: SelectOption[];
  themes: SelectOption[];
  colors: SelectOption[];
}

/**
 * Fetch field options from the API
 */
const fetchFieldOptions = async (): Promise<FieldOptionsResponse> => {
  const response = await apiFetch(`${config.apiUrl}/import/field-options`);
  if (!response.ok) {
    throw new Error('Failed to fetch field options');
  }
  return response.json();
};

/**
 * Hook to fetch and cache field options
 */
export const useFieldOptions = () => {
  return useQuery({
    queryKey: ['field-options'],
    queryFn: fetchFieldOptions,
    staleTime: 5 * 60 * 1000, // Cache for 5 minutes
    gcTime: 10 * 60 * 1000, // Keep in garbage collection for 10 minutes
    retry: 2,
    refetchOnWindowFocus: false,
  });
};

/**
 * Get options for a specific field key
 */
export const getOptionsForField = (
  fieldOptions: FieldOptionsResponse | undefined,
  fieldKey: string
): SelectOption[] => {
  if (!fieldOptions) return [];

  const fieldToOptionsMap: Record<string, keyof FieldOptionsResponse> = {
    supplier: 'suppliers',
    company: 'companies',
    tax_cat: 'taxCategories',
    artist: 'artists',
    ship_restrictions: 'shippingRestrictions',  // API returns 'shippingRestrictions'
    size_cat: 'sizes',  // API returns 'sizes'
    categories: 'categories',
    themes: 'themes',
    colors: 'colors',
  };

  const optionsKey = fieldToOptionsMap[fieldKey];
  if (optionsKey && fieldOptions[optionsKey]) {
    return fieldOptions[optionsKey];
  }

  return [];
};
