import { readdirSync, statSync } from "node:fs";
import { basename, join } from "node:path";

/**
 * Recursively get all files from a directory
 */
function getAllFiles(dir) {
	let results = [];
	for (const file of readdirSync(dir)) {
		const filePath = join(dir, file);
		const stat = statSync(filePath);
		if (stat.isDirectory()) {
			results = results.concat(getAllFiles(filePath));
		} else {
			results.push(filePath);
		}
	}
	return results;
}

/**
 * Main check function
 */
function checkRouteSpecs(baseDir) {
	const allFiles = getAllFiles(baseDir);

	// Collect base filenames (without extensions)
	const routeFiles = allFiles.filter((f) => f.endsWith(".route.ts"));
	const specFiles = allFiles.filter((f) => f.endsWith(".spec.ts"));

	const specNames = new Set(specFiles.map((f) => basename(f, ".spec.ts")));

	const missingSpecs = routeFiles.filter((routePath) => {
		const baseName = basename(routePath, ".route.ts");
		return !specNames.has(baseName);
	});

	if (missingSpecs.length > 0) {
		console.error("❌ Missing spec files for these routes:\n");
		for (const missing of missingSpecs) {
			console.error(`··-·${missing}`);
		}
		process.exit(1);
	} else {
		console.info("✅ All route files have corresponding spec files.");
	}
}

// Adjust paths based on your structure
checkRouteSpecs("backend");
