export interface ProductMediaLike {
  _id?: string;
  fileUrl?: string;
  updatedAt?: string;
  createdAt?: string;
  isDeleted?: boolean;
}

export function getPrimaryProductImage<T extends ProductMediaLike>(images?: T[]): T | undefined {
  if (!images?.length) {
    return undefined;
  }

  const activeImages = images.filter((image) => !image.isDeleted);
  const candidates = activeImages.length > 0 ? activeImages : images;

  return [...candidates].sort((left, right) => {
    const leftTime = new Date(left.updatedAt ?? left.createdAt ?? 0).getTime();
    const rightTime = new Date(right.updatedAt ?? right.createdAt ?? 0).getTime();
    return rightTime - leftTime;
  })[0];
}

export function appendImageCacheBuster(url: string, cacheKey?: string | number): string {
  if (!url || url.startsWith('blob:') || url.startsWith('data:')) {
    return url;
  }

  if (cacheKey == null || cacheKey === '') {
    return url;
  }

  const separator = url.includes('?') ? '&' : '?';
  return `${url}${separator}v=${encodeURIComponent(String(cacheKey))}`;
}

export function getProductImageDisplayUrl(
  fileUrl?: string,
  options?: {
    cacheKey?: string | number;
    overrideUrl?: string;
  }
): string {
  const sourceUrl = options?.overrideUrl ?? fileUrl ?? '';
  if (!sourceUrl) return '';

  return appendImageCacheBuster(sourceUrl, options?.cacheKey);
}
