/* @vitest-environment node */

import { describe, it, expect } from "vitest";
import { decideBranchUi, BRANCH_UI_DECISION } from "./branchUiDecision.js";

describe("lib/frontend/rbac/branchUiDecision", () => {
	it("returns FORBIDDEN for branch users accessing other branches", () => {
		const user = { userId: "u1", role: "branch", branchId: "NL01" };

		expect(decideBranchUi({ user, branch: "NL02" })).toBe(
			BRANCH_UI_DECISION.FORBIDDEN,
		);
	});

	it("returns ALLOWED for branch users accessing their own branch", () => {
		const user = { userId: "u1", role: "branch", branchId: "NL01" };

		expect(decideBranchUi({ user, branch: "NL01" })).toBe(
			BRANCH_UI_DECISION.ALLOWED,
		);
	});

	it("returns NOT_FOUND for admin-like users when branch is not in allowedBranches", () => {
		const admin = { userId: "u2", role: "admin", branchId: null };
		const superadmin = { userId: "u3", role: "superadmin", branchId: null };
		const dev = { userId: "u4", role: "dev", branchId: null };

		expect(
			decideBranchUi({
				user: admin,
				branch: "NL200",
				allowedBranches: ["NL01", "NL02"],
			}),
		).toBe(BRANCH_UI_DECISION.NOT_FOUND);

		expect(
			decideBranchUi({
				user: superadmin,
				branch: "NL200",
				allowedBranches: ["NL01", "NL02"],
			}),
		).toBe(BRANCH_UI_DECISION.NOT_FOUND);

		expect(
			decideBranchUi({
				user: dev,
				branch: "NL200",
				allowedBranches: ["NL01", "NL02"],
			}),
		).toBe(BRANCH_UI_DECISION.NOT_FOUND);
	});

	it("fails open (ALLOWED) for admin-like users when allowedBranches is not available", () => {
		const admin = { userId: "u2", role: "admin", branchId: null };
		const superadmin = { userId: "u3", role: "superadmin", branchId: null };

		expect(decideBranchUi({ user: admin, branch: "NL200" })).toBe(
			BRANCH_UI_DECISION.ALLOWED,
		);

		expect(decideBranchUi({ user: superadmin, branch: "NL200" })).toBe(
			BRANCH_UI_DECISION.ALLOWED,
		);
	});
});
