import { API_ORIGIN } from '@/constants/Api';
import Constants from 'expo-constants';
import { Image as ExpoImage, ImageProps as ExpoImageProps } from 'expo-image';
import React, { forwardRef, useMemo } from 'react';

// Construct User-Agent
const APP_NAME = Constants.expoConfig?.name || 'Out Live';
const APP_VERSION = Constants.expoConfig?.version || '1.1.5';
const USER_AGENT = `${APP_NAME}/${APP_VERSION} (iOS)`;

export type ImageProps = ExpoImageProps;

export const Image = forwardRef<ExpoImage, ImageProps>(({ source, ...props }, ref) => {
  const finalSource = useMemo(() => {
    if (!source) return source;

    const headers = {
      'User-Agent': USER_AGENT,
      'Referer': API_ORIGIN,
    };

    const addHeaders = (src: any) => {
      if (typeof src === 'number' || src === null || src === undefined) return src;
      if (typeof src === 'string') return { uri: src, headers };
      if (typeof src === 'object' && 'uri' in src) {
        return {
           ...src,
           headers: { ...headers, ...(src.headers || {}) }
        };
      }
      return src;
    };

    if (Array.isArray(source)) {
      return source.map(addHeaders);
    }
    
    return addHeaders(source);
  }, [source]);

  return <ExpoImage {...props} source={finalSource} ref={ref} />;
});

Image.displayName = 'Image';