import { auth } from '@/auth';
import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import PageContainer from '@/components/layout/page-container';
import { UserRoleAssignmentsPage } from '@/features/foundation/crm-role-assignments/components/user-role-assignments-page';
import { crmUserRoleAssignmentsQueryOptions } from '@/features/foundation/crm-role-assignments/api/queries';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { getQueryClient } from '@/lib/query-client';

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

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

  return (
    <PageContainer
      pageTitle='User Role Assignments'
      pageDescription='Assign multiple CRM role profiles to users with branch and product-type scope per assignment.'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to CRM user role assignments.
        </div>
      }
    >
      {canRead ? (
        <HydrationBoundary state={dehydrate(queryClient)}>
          <UserRoleAssignmentsPage />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}
