import { imageUploadService } from "./service";

/**
 * Extracts filename from an image URL (e.g., "/uploads/abc.webp" -> "abc.webp")
 */
function extractFilename(imageUrl: string): string | null {
  if (!imageUrl) return null;
  const filename = imageUrl.split("/").pop();
  return filename || null;
}

/**
 * Deletes a single image by its URL. Silently ignores errors.
 */
async function deleteImageByUrl(imageUrl: string): Promise<void> {
  const filename = extractFilename(imageUrl);
  if (filename) {
    try {
      await imageUploadService.deleteImage(filename);
    } catch {
      // Silently ignore deletion errors (file may already be deleted)
    }
  }
}

/**
 * Deletes a cover image by its URL. Returns a promise for parallel execution.
 */
export function deleteCoverImage(coverImage: string | null | undefined): Promise<void> {
  if (!coverImage) return Promise.resolve();
  return deleteImageByUrl(coverImage);
}

/**
 * Deletes multiple gallery images in parallel.
 */
export function deleteGalleryImages(galleryImages: unknown): Promise<void[]> {
  if (!galleryImages || !Array.isArray(galleryImages)) {
    return Promise.resolve([]);
  }

  const deletePromises = galleryImages
    .filter((url): url is string => typeof url === "string" && url.length > 0)
    .map((url) => deleteImageByUrl(url));

  return Promise.all(deletePromises);
}

/**
 * Deletes all images associated with a project (cover + gallery) in parallel.
 */
export async function deleteProjectImages(project: {
  coverImage?: string | null;
  galleryImages?: unknown;
}): Promise<void> {
  await Promise.all([
    deleteCoverImage(project.coverImage),
    deleteGalleryImages(project.galleryImages),
  ]);
}

/**
 * Deletes an image by URL (for single-image entities like Bold products).
 */
export async function deleteEntityImage(imageUrl: string | null | undefined): Promise<void> {
  await deleteCoverImage(imageUrl);
}

