import { getSignedUrlForKey, isS3Key } from "./s3-upload";

/**
 * Get a display URL for an image stored in the database
 * Handles S3 keys, local paths, and full URLs
 * @param imageUrl - Image URL/key from database
 * @returns Display URL ready for use in Image components
 */
export async function getImageDisplayUrl(
  imageUrl: string | null | undefined
): Promise<string | null> {
  if (!imageUrl) return null;

  // If it's already a full URL (http/https), return as is
  if (imageUrl.startsWith("http://") || imageUrl.startsWith("https://")) {
    return imageUrl;
  }

  // If it's a local path, return as is
  if (imageUrl.startsWith("/")) {
    return imageUrl;
  }

  // If it's an S3 key, get signed URL
  if (isS3Key(imageUrl)) {
    try {
      return await getSignedUrlForKey(imageUrl, 3600); // 1 hour expiry
    } catch (error) {
      console.error("Error getting signed URL for:", imageUrl, error);
      return null;
    }
  }

  // Fallback: treat as local path
  return imageUrl.startsWith("/") ? imageUrl : `/${imageUrl}`;
}

/**
 * Process multiple image URLs
 * @param images - Array of image objects with url property
 * @returns Array of images with signed URLs
 */
export async function processImageUrls<T extends { url: string }>(
  images: T[]
): Promise<(T & { displayUrl: string | null })[]> {
  return Promise.all(
    images.map(async (image) => ({
      ...image,
      displayUrl: await getImageDisplayUrl(image.url),
    }))
  );
}
