import { useIdentityAuthSession } from "@erp/identity/client"; import { showErrorToast, showSuccessToast } from "@repo/rdx-ui/helpers"; import { useQueryClient } from "@tanstack/react-query"; import { useState } from "react"; function resolveCompanyDisplayName(legalName: string, tradeName: string | null) { return tradeName?.trim() || legalName; } function resolveCompanySecondaryLabel(legalName: string, tradeName: string | null) { if (tradeName?.trim()) { return legalName; } return null; } function resolveCompanyInitials(name: string) { const words = name.trim().split(/\s+/).filter(Boolean); if (words.length === 0) { return "--"; } return words .slice(0, 2) .map((word) => word.charAt(0).toUpperCase()) .join(""); } function resolveErrorMessage(error: unknown) { if (error instanceof Error && error.message.trim().length > 0) { return error.message; } return "Please try again in a few seconds."; } export function useAppCompanySwitcherController() { const queryClient = useQueryClient(); const { activeCompany, availableCompanies, changeActiveCompany } = useIdentityAuthSession(); const [isChangingCompany, setIsChangingCompany] = useState(false); const activeCompanyView = activeCompany ? { id: activeCompany.id, name: resolveCompanyDisplayName(activeCompany.legalName, activeCompany.tradeName), secondaryLabel: resolveCompanySecondaryLabel( activeCompany.legalName, activeCompany.tradeName ), initials: resolveCompanyInitials( resolveCompanyDisplayName(activeCompany.legalName, activeCompany.tradeName) ), } : null; const companyOptions = availableCompanies.map((company) => { const name = resolveCompanyDisplayName(company.legalName, company.tradeName); return { id: company.id, name, secondaryLabel: resolveCompanySecondaryLabel(company.legalName, company.tradeName), initials: resolveCompanyInitials(name), isSelected: company.id === activeCompany?.id, }; }); const handleSelectCompany = async (companyId: string) => { if (isChangingCompany || companyId === activeCompany?.id) { return; } setIsChangingCompany(true); try { const nextActiveCompany = await changeActiveCompany(companyId); if (!nextActiveCompany) { showErrorToast("Unable to switch company", "The selected company is not available."); return; } await queryClient.cancelQueries(); queryClient.removeQueries({ type: "inactive" }); await queryClient.resetQueries({ type: "active" }); showSuccessToast( "Active company updated", `${resolveCompanyDisplayName(nextActiveCompany.legalName, nextActiveCompany.tradeName)} is now active.` ); } catch (error) { showErrorToast("Unable to switch company", resolveErrorMessage(error)); } finally { setIsChangingCompany(false); } }; return { activeCompany: activeCompanyView, companies: companyOptions, isChangingCompany, isDisabled: isChangingCompany || companyOptions.length <= 1, handleSelectCompany, }; }