import { auth } from '@/auth';
import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import PageContainer from '@/components/layout/page-container';
import { RoleManagementPage } from '@/features/foundation/role-management/components/role-management-page';
import { crmRoleProfilesQueryOptions } from '@/features/foundation/role-management/api/queries';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { getQueryClient } from '@/lib/query-client';

export default async function CrmRolesRoute() {
  const session = await auth();
  const canRead =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      session.user.activePermissions.includes(PERMISSIONS.crmRoleRead));
  const queryClient = getQueryClient();

  if (canRead) {
    void queryClient.prefetchQuery(crmRoleProfilesQueryOptions());
  }

  return (
    <PageContainer
      pageTitle='Roles & Permissions'
      pageDescription='Configure CRM role profiles, permission matrices, ownership visibility, and approval authority.'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to CRM role management.
        </div>
      }
    >
      {canRead ? (
        <HydrationBoundary state={dehydrate(queryClient)}>
          <RoleManagementPage />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}
