import {
	getBranchAccess,
	BRANCH_ACCESS,
} from "@/lib/frontend/rbac/branchAccess";
import { isAdminLike as isAdminLikeRole } from "@/lib/frontend/auth/roles";

export const BRANCH_UI_DECISION = Object.freeze({
	ALLOWED: "allowed",
	FORBIDDEN: "forbidden",
	NOT_FOUND: "not-found",
});

/**
 * Decide which UI outcome should be shown for a branch route.
 *
 * Notes:
 * - This function assumes the user is authenticated (handled by AuthProvider).
 * - For admin-like roles we can optionally validate branch existence using `allowedBranches`
 *   from GET /api/branches. If the list is not available, we fail open.
 *
 * @param {{
 *   user: { userId: string, role: string, branchId: string|null },
 *   branch: string,
 *   allowedBranches?: string[]|null
 * }} input
 * @returns {"allowed"|"forbidden"|"not-found"}
 */
export function decideBranchUi({ user, branch, allowedBranches = null }) {
	const access = getBranchAccess(user, branch);

	if (access === BRANCH_ACCESS.FORBIDDEN) {
		return BRANCH_UI_DECISION.FORBIDDEN;
	}

	// Only admin-like roles may validate existence across branches.
	if (isAdminLikeRole(user.role)) {
		if (Array.isArray(allowedBranches) && !allowedBranches.includes(branch)) {
			return BRANCH_UI_DECISION.NOT_FOUND;
		}
	}

	return BRANCH_UI_DECISION.ALLOWED;
}
