import { cpSync, existsSync, mkdirSync } from 'node:fs'
import path from 'node:path'

/**
 * Copy a file between two directories.
 * It handles the creation of the destDir case its needed.
 * @param sourceDir Path of the source directory.
 * @param destDir Path of the destination directory.
 * @param file Name of the file.
 * @param rename New name of the file.
 */
export function copyFile(
  sourceDir: string,
  destDir: string,
  file: string,
  rename?: string
): void {
  // Create the destDir directory if it doesn't exist
  if (!existsSync(destDir)) {
    mkdirSync(destDir, { recursive: true })
  }

  const sourceFile = path.join(sourceDir, file)
  const destFile = path.join(destDir, rename ?? file)

  try {
    cpSync(sourceFile, destFile, { recursive: true })
  } catch (e) {
    console.error(e)
  }
}
