import { atom } from 'jotai';
import { getProductRetrievalFunction } from './productRetrievalAdapter';
import { ProductRetrievalParams, ProductRetrievalResult } from './types';

interface ProductRetrievalState {
  data: ProductRetrievalResult | null;
  loading: boolean;
  error: string | null;
  lastProductIds: string[] | null;
}

export const productRetrievalAtom = atom<ProductRetrievalState>({
  data: null,
  loading: false,
  error: null,
  lastProductIds: null,
});

export const performProductRetrievalAtom = atom(
  null,
  async (get, set, params: ProductRetrievalParams) => {
    const currentState = get(productRetrievalAtom);

    if (currentState.loading) {
      return; // Prevent concurrent retrievals
    }

    set(productRetrievalAtom, {
      data: null,
      loading: true,
      error: null,
      lastProductIds: params.productIds,
    });

    try {
      const retrieveProducts = getProductRetrievalFunction();
      const result = await retrieveProducts(params);
      set(productRetrievalAtom, {
        data: result,
        loading: false,
        error: null,
        lastProductIds: params.productIds,
      });
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred';
      set(productRetrievalAtom, {
        data: null,
        loading: false,
        error: errorMessage,
        lastProductIds: params.productIds,
      });
    }
  },
);

// Get just the products array (already normalized by service)
export const retrievedProductsAtom = atom(get => {
  const retrievalData = get(productRetrievalAtom).data;
  return retrievalData?.products || [];
});
