export const ADMIN_USERS_SORT = Object.freeze({
	DEFAULT: "default",
	ROLE_RIGHTS: "role_rights",
	BRANCH_ASC: "branch_asc",
});

const ROLE_RANK = Object.freeze({
	superadmin: 4,
	dev: 3,
	admin: 2,
	branch: 1,
});

function normalizeRole(value) {
	return String(value ?? "")
		.trim()
		.toLowerCase();
}

function toRoleRank(value) {
	const role = normalizeRole(value);
	return ROLE_RANK[role] ?? 0;
}

function toBranchNumber(branchId) {
	const raw = String(branchId ?? "").trim();
	if (!raw) return null;

	const match = /^NL(\d+)$/i.exec(raw);
	if (!match) return null;

	const n = Number(match[1]);
	return Number.isInteger(n) ? n : null;
}

function compareBranchAscNullLast(a, b) {
	const an = toBranchNumber(a);
	const bn = toBranchNumber(b);

	if (an !== null && bn !== null) return an - bn;
	if (an === null && bn !== null) return 1;
	if (an !== null && bn === null) return -1;

	return String(a ?? "").localeCompare(String(b ?? ""), "de", {
		sensitivity: "base",
	});
}

function compareUsernamesAsc(a, b) {
	return String(a ?? "").localeCompare(String(b ?? ""), "de", {
		sensitivity: "base",
	});
}

function compareIdsAsc(a, b) {
	return String(a ?? "").localeCompare(String(b ?? ""), "en");
}

export function normalizeAdminUsersSortMode(value) {
	const mode = String(value ?? "").trim();
	if (!mode) return ADMIN_USERS_SORT.DEFAULT;

	if (Object.values(ADMIN_USERS_SORT).includes(mode)) {
		return mode;
	}

	return null;
}

export function compareUsersByRoleRights(a, b) {
	const roleCmp = toRoleRank(b?.role) - toRoleRank(a?.role);
	if (roleCmp !== 0) return roleCmp;

	const branchCmp = compareBranchAscNullLast(a?.branchId, b?.branchId);
	if (branchCmp !== 0) return branchCmp;

	const usernameCmp = compareUsernamesAsc(a?.username, b?.username);
	if (usernameCmp !== 0) return usernameCmp;

	return compareIdsAsc(a?.id ?? a?._id, b?.id ?? b?._id);
}

export function compareUsersByBranchAsc(a, b) {
	const branchCmp = compareBranchAscNullLast(a?.branchId, b?.branchId);
	if (branchCmp !== 0) return branchCmp;

	const roleCmp = toRoleRank(b?.role) - toRoleRank(a?.role);
	if (roleCmp !== 0) return roleCmp;

	const usernameCmp = compareUsernamesAsc(a?.username, b?.username);
	if (usernameCmp !== 0) return usernameCmp;

	return compareIdsAsc(a?.id ?? a?._id, b?.id ?? b?._id);
}

export function sortAdminUsers(items, sortMode) {
	const list = Array.isArray(items) ? [...items] : [];

	if (sortMode === ADMIN_USERS_SORT.ROLE_RIGHTS) {
		return list.sort(compareUsersByRoleRights);
	}

	if (sortMode === ADMIN_USERS_SORT.BRANCH_ASC) {
		return list.sort(compareUsersByBranchAsc);
	}

	return list;
}

