import { auth } from '@/auth';
import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import PageContainer from '@/components/layout/page-container';
import { ReminderPolicySettings } from '@/features/foundation/approval-automation/components/reminder-policy-settings';
import {
  approvalReminderPoliciesOptions,
  pendingApprovalAutomationQueueOptions
} from '@/features/foundation/approval-automation/api/queries';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { getQueryClient } from '@/lib/query-client';

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

  const queryClient = getQueryClient();
  if (canRead) {
    void queryClient.prefetchQuery(approvalReminderPoliciesOptions());
    void queryClient.prefetchQuery(pendingApprovalAutomationQueueOptions());
  }

  return (
    <PageContainer
      pageTitle='Approval Reminder Policies'
      pageDescription='Configure SLA, reminder timing, timeout actions, and monitor the pending approval automation queue.'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to approval reminder policies.
        </div>
      }
    >
      {canRead ? (
        <HydrationBoundary state={dehydrate(queryClient)}>
          <ReminderPolicySettings />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}
