import assert from 'node:assert';
import { promises as fsPromises } from 'node:fs';
import BoxError from './boxerror.js';
import safe from 'safetydance';

// cross device file rename
async function renameFile(sourcePath, destPath) {
    assert.strictEqual(typeof sourcePath, 'string');
    assert.strictEqual(typeof destPath, 'string');
    const [renameError] = await safe(fsPromises.rename(sourcePath, destPath));
    if (renameError) {
        if (renameError.code === 'EXDEV') {
            const [copyError] = await safe(fsPromises.copyFile(sourcePath, destPath));
            if (copyError) throw new BoxError(BoxError.FS_ERROR, copyError);
            const [unlinkError] = await safe(fsPromises.unlink(sourcePath));
            if (unlinkError) throw new BoxError(BoxError.FS_ERROR, unlinkError);
        } else {
            throw new BoxError(BoxError.FS_ERROR, renameError);
        }
    }
}

export default { renameFile };
