import { deleteCloudinaryImageByUrl } from "~/lib/cloudinary.server";
import { logger } from "~/lib/logger";
import { isSportIconUrlUsed } from "~/models/sport";

interface DeleteSportIconIfUnusedArgs {
  iconUrl: string;
  excludeSportId?: string;
  reason: "replaced" | "unused";
}

export async function deleteSportIconIfUnused({
  iconUrl,
  excludeSportId,
  reason,
}: DeleteSportIconIfUnusedArgs): Promise<void> {
  try {
    if (await isSportIconUrlUsed(iconUrl, excludeSportId)) {
      return;
    }
  } catch (error) {
    logger.error("Failed to check whether sport icon is reused; skipping Cloudinary cleanup:", error);
    return;
  }

  deleteCloudinaryImageByUrl(iconUrl).catch((error) => {
    logger.error(`Failed to delete ${reason} sport icon from Cloudinary:`, error);
  });
}
