import { describe, it, expect } from "vitest";
import { validateEnv, MIN_SESSION_SECRET_LENGTH } from "./validateEnv.js";

function validSecret() {
	return "x".repeat(MIN_SESSION_SECRET_LENGTH);
}

describe("validateEnv", () => {
	it("returns normalized config for a valid env", () => {
		const cfg = validateEnv({
			MONGODB_URI: "mongodb://localhost:27017/rhl",
			SESSION_SECRET: validSecret(),
			NAS_ROOT_PATH: "/mnt/niederlassungen/",
			PORT: "3000",
		});

		expect(cfg.mongodbUri).toBe("mongodb://localhost:27017/rhl");
		expect(cfg.sessionSecret).toBe(validSecret());
		expect(cfg.nasRootPath).toBe("/mnt/niederlassungen");
		expect(cfg.nodeEnv).toBe("development");
		expect(cfg.port).toBe(3000);
		expect(cfg.searchProvider).toBe("fs");
	});

	it("accepts optional SESSION_COOKIE_SECURE=false", () => {
		expect(() =>
			validateEnv({
				MONGODB_URI: "mongodb://localhost:27017/rhl",
				SESSION_SECRET: validSecret(),
				NAS_ROOT_PATH: "/mnt/niederlassungen",
				NODE_ENV: "production",
				SESSION_COOKIE_SECURE: "false",
			})
		).not.toThrow();
	});

	it("rejects invalid SEARCH_PROVIDER values", () => {
		expect(() =>
			validateEnv({
				MONGODB_URI: "mongodb://localhost:27017/rhl",
				SESSION_SECRET: validSecret(),
				NAS_ROOT_PATH: "/mnt/niederlassungen",
				SEARCH_PROVIDER: "nope",
			})
		).toThrow(/SEARCH_PROVIDER/i);
	});

	it("requires Qsirch env keys when SEARCH_PROVIDER=qsirch", () => {
		expect(() =>
			validateEnv({
				MONGODB_URI: "mongodb://localhost:27017/rhl",
				SESSION_SECRET: validSecret(),
				NAS_ROOT_PATH: "/mnt/niederlassungen",
				SEARCH_PROVIDER: "qsirch",
			})
		).toThrow(
			/QSIRCH_BASE_URL|QSIRCH_ACCOUNT|QSIRCH_PASSWORD|QSIRCH_PATH_PREFIX/i
		);
	});

	it("accepts a valid qsirch configuration", () => {
		expect(() =>
			validateEnv({
				MONGODB_URI: "mongodb://localhost:27017/rhl",
				SESSION_SECRET: validSecret(),
				NAS_ROOT_PATH: "/mnt/niederlassungen",
				SEARCH_PROVIDER: "qsirch",
				QSIRCH_BASE_URL: "http://192.168.0.22:8080",
				QSIRCH_ACCOUNT: "rhl_search",
				QSIRCH_PASSWORD: "super-secret",
				QSIRCH_PATH_PREFIX: "/Niederlassungen",
				QSIRCH_DATE_FIELD: "modified",
				QSIRCH_MODE: "sync",
			})
		).not.toThrow();
	});
});
