"use strict";

require("./helpers/warmup-webpack");

const path = require("path");
const fs = require("graceful-fs");
const { Volume, createFsFromVolume } = require("memfs");
/** @type {(path: string, callback: (err?: unknown) => void) => void} */
const rimraf = require("rimraf");
const expectNoDeprecations = require("./helpers/expectNoDeprecations");

/**
 * @param {import("../").Configuration} config config
 * @returns {import("../").Compiler} compiler
 */
const createCompiler = (config) => {
	const webpack = require("..");

	const compiler = /** @type {import("../").Compiler} */ (webpack(config));
	compiler.outputFileSystem = /** @type {EXPECTED_ANY} */ (
		createFsFromVolume(new Volume())
	);
	return compiler;
};

const tempFolderPath = path.join(__dirname, "ChangesAndRemovalsTemp");
const tempFilePath = path.join(tempFolderPath, "temp-file.js");
const tempFile2Path = path.join(tempFolderPath, "temp-file2.js");

const createSingleCompiler = () =>
	createCompiler({
		entry: tempFilePath,
		output: {
			path: tempFolderPath,
			filename: "bundle.js"
		}
	});

/**
 * @param {import("../").Compiler} compiler compiler
 * @param {() => void} action action
 */
const onceDone = (compiler, action) => {
	let initial = true;
	compiler.hooks.done.tap("ChangesAndRemovalsTest", () => {
		if (!initial) return;
		initial = false;
		setTimeout(action, 1000);
	});
};

/**
 * @param {import("../").Compiler} compiler compiler
 * @returns {{ removed: string[] | undefined, modified: string[] | undefined }} changes
 */
const getChanges = (compiler) => {
	const modifiedFiles = compiler.modifiedFiles;
	const removedFiles = compiler.removedFiles;
	return {
		removed: removedFiles && [...removedFiles],
		modified: modifiedFiles && [...modifiedFiles]
	};
};

/**
 * @param {(err?: unknown) => void} callback callback
 */
function cleanup(callback) {
	rimraf(tempFolderPath, callback);
}

/**
 * @returns {void}
 */
function createFiles() {
	fs.mkdirSync(tempFolderPath, { recursive: true });

	fs.writeFileSync(
		tempFilePath,
		"module.exports = function temp() {return 'temp file';};\n require('./temp-file2')",
		"utf8"
	);

	fs.writeFileSync(
		tempFile2Path,
		"module.exports = function temp2() {return 'temp file 2';};",
		"utf8"
	);
}

// Bun's fs.watch surfaces unlink events differently from Node, so watchpack
// reports the removed file inconsistently across runs; skip on Bun.
const itSkipBun = process.versions.bun ? it.skip : it;

expectNoDeprecations();

describe("ChangesAndRemovals", () => {
	beforeEach((done) => {
		cleanup((err) => {
			if (err) return done(err);
			createFiles();
			// Wait 2.5s after creating the files,
			// otherwise the newly-created files will trigger the webpack watch mode to re-compile.
			setTimeout(done, 2500);
		});
	});

	afterEach(cleanup);

	if (process.env.NO_WATCH_TESTS) {
		// eslint-disable-next-line jest/no-disabled-tests
		it.skip("watch tests excluded", () => {});

		return;
	}

	it("should not track modified/removed files during initial watchRun", (done) => {
		const compiler = createSingleCompiler();
		const watchRunFinished = /** @type {Promise<void>} */ (
			new Promise((resolve) => {
				compiler.hooks.watchRun.tap("ChangesAndRemovalsTest", (compiler) => {
					expect(getChanges(compiler)).toEqual({
						removed: undefined,
						modified: undefined
					});
					resolve();
				});
			})
		);
		const watcher = /** @type {import("../").Watching} */ (
			compiler.watch({ aggregateTimeout: 200 }, (err) => {
				if (err) done(err);
			})
		);

		watchRunFinished.then(() => {
			watcher.close(done);
		});
	});

	it("should track modified files when they've been modified", (done) => {
		const compiler = createSingleCompiler();
		/** @type {import("../").Watching | null} */
		let watcher = null;

		compiler.hooks.watchRun.tap("ChangesAndRemovalsTest", (compiler) => {
			if (!watcher) return;
			if (!compiler.modifiedFiles) return;
			expect(getChanges(compiler)).toEqual({
				modified: [tempFilePath],
				removed: []
			});
			watcher.close(done);
			watcher = null;
		});

		watcher = /** @type {import("../").Watching} */ (
			compiler.watch({ aggregateTimeout: 200 }, (err) => {
				if (err) done(err);
			})
		);

		onceDone(compiler, () => {
			fs.appendFileSync(tempFilePath, "\nlet x = 'file modified';");
		});
	});

	itSkipBun("should track removed file when removing file", (done) => {
		const compiler = createSingleCompiler();
		/** @type {import("../").Watching | null} */
		let watcher = null;

		compiler.hooks.watchRun.tap("ChangesAndRemovalsTest", (compiler) => {
			if (!watcher) return;
			if (!compiler.modifiedFiles) return;
			expect(getChanges(compiler)).toEqual({
				removed: [tempFilePath],
				modified: []
			});
			watcher.close(done);
			watcher = null;
		});

		watcher = /** @type {import("../").Watching} */ (
			compiler.watch({ aggregateTimeout: 200 }, (err) => {
				if (err) done(err);
			})
		);

		onceDone(compiler, () => {
			fs.unlinkSync(tempFilePath);
		});
	});
});
