import os__default from 'node:os';
import fs__default from 'node:fs';
import path__default from 'node:path';
import process__default from 'node:process';
import { m as moveFile } from '../shared/ccjk.Bx_rmYfN.mjs';
import { c as chunkedExec } from '../shared/ccjk.T_cX87dY.mjs';
import 'node:util';
import 'node:child_process';
import 'node:url';
import '../shared/ccjk.KfSWcGlE.mjs';

const isOlderThanMountainLion = Number(os__default.release().split('.')[0]) < 12;

// Binary source: https://github.com/sindresorhus/macos-trash
const binary = new URL('macos-trash', import.meta.url);

async function macOS(paths) {
	if (isOlderThanMountainLion) {
		throw new Error('macOS 10.12 or later required');
	}

	try {
		await chunkedExec(binary, paths, 1000);
	} catch (error) {
		const message = String(error?.stderr || error?.message || '');
		const shouldFallback = message.includes('couldn’t be moved to the trash because you don’t have permission')
			|| process__default.env.TRASH_FALLBACK === '1';

		if (!shouldFallback) {
			throw error;
		}

		// Fallback: move to user's Trash folder when the binary cannot run due to permissions.
		const trashDirectories = [
			path__default.join(os__default.homedir(), '.Trash'),
			path__default.join(process__default.cwd(), '.Trash'),
		];

		await Promise.all(paths.map(async filePath => {
			const base = path__default.basename(filePath);
			let lastError;

			/* eslint-disable no-await-in-loop */
			for (const dir of trashDirectories) {
				try {
					await fs__default.promises.mkdir(dir, {recursive: true});
					let destination = path__default.join(dir, base);
					let counter = 1;

					while (fs__default.existsSync(destination)) {
						destination = path__default.join(dir, `${base} ${counter++}`);
					}

					await moveFile(filePath, destination, {overwrite: false});
					return;
				} catch (error_) {
					lastError = error_;
				}
			}
			/* eslint-enable no-await-in-loop */

			if (lastError) {
				throw lastError;
			}
		}));
	}
}

export { macOS as default };
