import { useEffect, useState } from 'react';
import CommerceApiClient from 'src/application/commerce-api';

/**
 * Fetches the product image URL for the given product ID via CommerceApiClient.retrieveProducts.
 * Returns undefined while loading, on error, or when productId is not provided.
 */
export const useProductImageUrl = (productId: string | undefined): string | undefined => {
  const [imageUrl, setImageUrl] = useState<string | undefined>(undefined);

  useEffect(() => {
    if (!productId) {
      setImageUrl(undefined);
      return undefined;
    }
    let cancelled = false;
    CommerceApiClient.retrieveProducts([productId]).then(
      result => {
        if (!cancelled && result.products?.length > 0) {
          setImageUrl(result.products[0].imageUrl);
        } else if (!cancelled) {
          setImageUrl(undefined);
        }
      },
      () => {
        if (!cancelled) setImageUrl(undefined);
      },
    );
    return () => {
      cancelled = true;
    };
  }, [productId]);

  return imageUrl;
};
