import * as readline from "node:readline";

//#region src/db/utils.ts
const isLocalhostUrl = (url) => {
	if (!url) return false;
	try {
		const parsed = new URL(url);
		return parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1" || parsed.hostname === "::1";
	} catch {
		return url.includes("localhost") || url.includes("127.0.0.1");
	}
};
const askConfirmation = (question) => {
	const rl = readline.createInterface({
		input: process.stdin,
		output: process.stdout
	});
	return new Promise((resolve) => {
		rl.question(question, (answer) => {
			rl.close();
			resolve(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
		});
	});
};
const confirmMigration = async (connectionString) => {
	if (!connectionString) {
		console.error("❌ Error: Database URL is not set.");
		process.exit(1);
	}
	if (process.env.CI === "true") {
		console.log("CI environment detected — skipping interactive confirmation.");
		return true;
	}
	if (!isLocalhostUrl(connectionString)) {
		console.warn("⚠️  Warning: Database URL is not pointing to localhost. This operation may modify a production database.");
		if (!await askConfirmation("Do you want to proceed? (y/n): ")) {
			console.log("Migration cancelled.");
			process.exit(0);
		}
		console.log("");
	}
	return true;
};

//#endregion
export { askConfirmation, confirmMigration, isLocalhostUrl };