import fs from "node:fs";
import { Resource } from "../resource.js";
import { ignore } from "../util/ignore.js";
import { logger } from "../util/logger.js";
/**
 * CopyFile Resource
 *
 * Copies a file from a source location to a destination location.
 *
 * @example
 * // Copy a file to a new location
 * const copiedFile = await CopyFile("config-copy", {
 *   src: "config.json",
 *   dest: "backup/config.json"
 * });
 *
 * @example
 * // Copy a file without overwriting if destination exists
 * const safeCopy = await CopyFile("safe-copy", {
 *   src: "data.json",
 *   dest: "backup/data.json",
 *   overwrite: false
 * });
 */
export const CopyFile = Resource("fs::CopyFile", async function (_id, props) {
    const { src, dest, overwrite = true } = props;
    if (this.phase === "delete") {
        // When deleting, remove the destination file
        await ignore("ENOENT", async () => fs.promises.unlink(dest));
        return this.destroy();
    }
    try {
        // Check if source file exists
        await fs.promises.access(src, fs.constants.F_OK);
        // If this is an update and the destination has changed, delete the old file
        if (this.phase === "update" &&
            this.output?.dest &&
            this.output.dest !== dest) {
            await ignore("ENOENT", async () => fs.promises.unlink(this.output.dest));
        }
        // Check if destination file exists
        const destinationExists = await fs.promises
            .access(dest, fs.constants.F_OK)
            .then(() => true)
            .catch(() => false);
        // Copy file if destination doesn't exist or overwrite is true
        if (!destinationExists || overwrite) {
            await fs.promises.copyFile(src, dest);
        }
        return {
            src,
            dest,
            overwrite,
            copied: true,
            createdAt: Date.now(),
        };
    }
    catch (error) {
        logger.error("Error copying file:", error);
        throw error;
    }
});
//# sourceMappingURL=copy-file.js.map