import * as fs from "node:fs";
import type { FSWatcher, WatchListener } from "node:fs";

export const FS_WATCH_RETRY_DELAY_MS = 5000;

export function closeWatcher(watcher: FSWatcher | null | undefined): void {
	if (!watcher) {
		return;
	}

	try {
		watcher.close();
	} catch {
		// Ignore watcher close errors
	}
}

export function watchWithErrorHandler(
	path: string,
	listener: WatchListener<string>,
	onError: (error?: unknown) => void,
): FSWatcher | null {
	try {
		const watcher = fs.watch(path, listener);
		watcher.on("error", onError);
		return watcher;
	} catch (error) {
		onError(error);
		return null;
	}
}
