/* @vitest-environment node */

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";

vi.mock("@/lib/auth/session", () => ({
	getSession: vi.fn(),
}));

import { getSession } from "@/lib/auth/session";
import { GET, dynamic } from "./route.js";

describe("GET /api/branches", () => {
	let tmpRoot;
	const originalNasRoot = process.env.NAS_ROOT_PATH;

	beforeEach(async () => {
		vi.clearAllMocks();
		tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "api-branches-"));
		process.env.NAS_ROOT_PATH = tmpRoot;
	});

	afterEach(async () => {
		process.env.NAS_ROOT_PATH = originalNasRoot;
		if (tmpRoot) {
			await fs.rm(tmpRoot, { recursive: true, force: true });
		}
	});

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

	it("returns 401 when unauthenticated", async () => {
		getSession.mockResolvedValue(null);

		const res = await GET();
		expect(res.status).toBe(401);

		const body = await res.json();
		expect(body).toEqual({
			error: { message: "Unauthorized", code: "AUTH_UNAUTHENTICATED" },
		});
	});

	it("returns only the own branch for branch users", async () => {
		getSession.mockResolvedValue({
			role: "branch",
			branchId: "NL01",
			userId: "u1",
		});

		await fs.mkdir(path.join(tmpRoot, "NL01"), { recursive: true });
		await fs.mkdir(path.join(tmpRoot, "NL02"), { recursive: true });

		const res = await GET();
		expect(res.status).toBe(200);

		const body = await res.json();
		expect(body.branches).toEqual(["NL01"]);
	});

	it("returns all branches for admin/dev users", async () => {
		getSession.mockResolvedValue({
			role: "admin",
			branchId: null,
			userId: "u2",
		});

		await fs.mkdir(path.join(tmpRoot, "NL01"), { recursive: true });
		await fs.mkdir(path.join(tmpRoot, "NL02"), { recursive: true });

		const res = await GET();
		expect(res.status).toBe(200);

		const body = await res.json();
		expect([...body.branches].sort()).toEqual(["NL01", "NL02"]);
	});

	it("returns 500 when NAS_ROOT_PATH is invalid (authenticated)", async () => {
		getSession.mockResolvedValue({
			role: "admin",
			branchId: null,
			userId: "u2",
		});

		process.env.NAS_ROOT_PATH = path.join(tmpRoot, "does-not-exist");

		const res = await GET();
		expect(res.status).toBe(500);

		const body = await res.json();
		expect(body).toEqual({
			error: { message: "Internal server error", code: "FS_STORAGE_ERROR" },
		});
	});
});
