import { auth } from '@/auth';
import PageContainer from '@/components/layout/page-container';
import ApprovalListing from '@/features/foundation/approval/components/approval-listing';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { searchParamsCache } from '@/lib/searchparams';
import type { SearchParams } from 'nuqs/server';

export const metadata = {
  title: 'Dashboard: CRM Approvals'
};

type PageProps = {
  searchParams: Promise<SearchParams>;
};

export default async function ApprovalsRoute(props: PageProps) {
  const searchParams = await props.searchParams;
  const session = await auth();
  const canRead =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmApprovalRead)));

  searchParamsCache.parse(searchParams);

  return (
    <PageContainer
      pageTitle='อนุมัติเอกสาร'
      pageDescription='คิวงานอนุมัติเอกสารสำหรับใบเสนอราคา พร้อมลำดับอนุมัติและประวัติการดำเนินการ'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to CRM approvals.
        </div>
      }
    >
      {canRead ? <ApprovalListing /> : null}
    </PageContainer>
  );
}
