import type { ISiteRoles } from "@ax/types";

const GENERIC_DOMAINS = new Set(["gmail", "hotmail", "outlook", "yahoo", "icloud", "live", "msn", "aol"]);

const getCompanyFromEmail = (email: string): string => {
	const domain = email.split("@")[1] ?? "";
	const company = domain.substring(0, domain.lastIndexOf("."));
	if (GENERIC_DOMAINS.has(company)) return "";
	return company.charAt(0).toUpperCase() + company.slice(1);
};

const getMostFrequentRole = (userRoles: ISiteRoles[]): number | null => {
	const roleCounts: Record<number, number> = {};

	userRoles.forEach(({ roles }) => {
		roles.forEach((roleId) => {
			roleCounts[roleId] = (roleCounts[roleId] || 0) + 1;
		});
	});

	if (Object.keys(roleCounts).length === 0) return null;

	return Number(Object.entries(roleCounts).reduce((prev, curr) => (curr[1] > prev[1] ? curr : prev))[0]);
};

export { getCompanyFromEmail, getMostFrequentRole };
