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

/**
 * A centralized utility to clean up files created during tests.
 * It iterates through a list of file paths and attempts to delete each one.
 * It gracefully handles errors for files that don't exist (e.g., already deleted
 * or never created due to a test failure).
 */
export const cleanupFiles = async (filePaths: (string | undefined | null)[]) => {
  const validPaths = filePaths.filter((p): p is string => !!p);
  if (validPaths.length === 0) {
    return;
  }

  logger.debug(`Cleaning up ${validPaths.length} test-created file(s)...`);

  const cleanupPromises = validPaths.map(async (filePath) => {
    try {
      await fs.unlink(filePath);
    } catch (error) {
      if (error instanceof Error && (error as NodeJS.ErrnoException).code !== 'ENOENT') {
        logger.error({ error, filePath }, 'Failed to delete test file during cleanup.');
      }
    }
  });

  await Promise.allSettled(cleanupPromises);
};