// src/utils/fileUtils.ts
import fs from 'node:fs/promises';
import { logger } from '../services/logger.server';

/**
 * Safely deletes a file from the filesystem, ignoring errors if the file doesn't exist.
 * @param file The multer file object to delete.
 */
export const cleanupUploadedFile = async (file?: Express.Multer.File) => {
  if (!file) return;
  try {
    await fs.unlink(file.path);
  } catch (err) {
    logger.warn({ err, filePath: file.path }, 'Failed to clean up uploaded file.');
  }
};

/**
 * Safely deletes multiple files from the filesystem.
 * @param files An array of multer file objects to delete.
 */
export const cleanupUploadedFiles = async (files?: Express.Multer.File[]) => {
  if (!files || !Array.isArray(files)) return;
  // Use Promise.all to run cleanups in parallel for efficiency.
  await Promise.all(files.map((file) => cleanupUploadedFile(file)));
};