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

/**
 * Safely cleans up files from the filesystem.
 * Designed to be used in `afterAll` or `afterEach` hooks in integration tests.
 *
 * @param filePaths An array of file paths to clean up.
 */
export const cleanupFiles = async (filePaths: string[]) => {
  if (!filePaths || filePaths.length === 0) {
    logger.info('[Test Cleanup] No file paths provided for cleanup.');
    return;
  }

  logger.info(`[Test Cleanup] Starting filesystem cleanup for ${filePaths.length} file(s)...`);

  try {
    await Promise.all(
      filePaths.map(async (filePath) => {
        try {
          await fs.unlink(filePath);
          logger.debug(`[Test Cleanup] Successfully deleted file: ${filePath}`);
        } catch (err: any) {
          // Ignore "file not found" errors, but log other errors.
          if (err.code === 'ENOENT') {
            logger.debug(`[Test Cleanup] File not found, skipping: ${filePath}`);
          } else {
            logger.warn(
              { err, filePath },
              '[Test Cleanup] Failed to clean up file from filesystem.',
            );
          }
        }
      }),
    );

    logger.info('[Test Cleanup] Finished filesystem cleanup successfully.');
  } catch (error) {
    logger.error(
      { error },
      '[Test Cleanup] CRITICAL: An error occurred during filesystem cleanup.',
    );
    throw error; // Re-throw to fail the test suite if cleanup fails
  }
};