// app/api/health/route.test.js
import { describe, it, expect, vi, beforeEach } from "vitest";

// Mock the DB helper and fs.promises before importing the route
vi.mock("@/lib/db", () => {
	return {
		getDb: vi.fn(),
	};
});

vi.mock("fs/promises", () => {
	return {
		default: {
			readdir: vi.fn(),
		},
	};
});

import { GET as getHealth, dynamic } from "./route.js";
import { getDb } from "@/lib/db";
import fs from "fs/promises";

const mockedGetDb = getDb;
const mockedReaddir = fs.readdir;

beforeEach(() => {
	vi.resetAllMocks();
});

describe("GET /api/health", () => {
	it('exports dynamic="force-dynamic" (RHL-006)', () => {
		expect(dynamic).toBe("force-dynamic");
	});

	it("reports db=ok and nas with entries when both are healthy", async () => {
		mockedGetDb.mockResolvedValue({
			command: vi.fn().mockResolvedValue({ ok: 1 }),
		});
		mockedReaddir.mockResolvedValue(["NL01", "NL02"]);

		const req = new Request("http://localhost/api/health");
		const res = await getHealth(req);
		expect(res.status).toBe(200);

		const body = await res.json();
		expect(body.db).toBe("ok");
		expect(body.nas.path).toBe(
			process.env.NAS_ROOT_PATH || "/mnt/niederlassungen"
		);
		expect(body.nas.entriesSample).toEqual(["NL01", "NL02"]);
	});

	it("reports db error when getDb throws", async () => {
		mockedGetDb.mockRejectedValue(new Error("DB down"));
		mockedReaddir.mockResolvedValue(["NL01"]);

		const req = new Request("http://localhost/api/health");
		const res = await getHealth(req);
		const body = await res.json();

		expect(body.db).toBe("error: DB down");
		// NAS is still ok in this scenario
		expect(body.nas.entriesSample).toEqual(["NL01"]);
	});

	it("reports nas error when readdir fails", async () => {
		mockedGetDb.mockResolvedValue({
			command: vi.fn().mockResolvedValue({ ok: 1 }),
		});
		mockedReaddir.mockRejectedValue(new Error("ENOENT"));

		const req = new Request("http://localhost/api/health");
		const res = await getHealth(req);
		const body = await res.json();

		expect(body.db).toBe("ok");
		expect(body.nas).toBe("error: ENOENT");
	});
});
