import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { auth } from '@/auth';
import PageContainer from '@/components/layout/page-container';
import {
  crmReportCatalogQueryOptions,
  crmReportFiltersQueryOptions
} from '@/features/crm/reports/api/queries';
import { ReportCatalog } from '@/features/crm/reports/components/report-catalog';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { getQueryClient } from '@/lib/query-client';

export const metadata = {
  title: 'CRM Reports'
};

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

  if (canRead) {
    void queryClient.prefetchQuery(crmReportCatalogQueryOptions());
    void queryClient.prefetchQuery(crmReportFiltersQueryOptions());
  }

  return (
    <PageContainer
      pageTitle='CRM Reports'
      pageDescription='Report center foundation, shared filters, and catalog for upcoming CRM analytics modules.'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to the CRM report center.
        </div>
      }
    >
      {canRead ? (
        <HydrationBoundary state={dehydrate(queryClient)}>
          <ReportCatalog />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}
