import { auth } from '@/auth';
import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import PageContainer from '@/components/layout/page-container';
import { CustomerDetail } from '@/features/crm/customers/components/customer-detail';
import { customerByIdOptions, customerContactsOptions } from '@/features/crm/customers/api/queries';
import { getCustomerReferenceData } from '@/features/crm/customers/server/service';
import { listCustomerEnquiryRelations } from '@/features/crm/enquiries/server/service';
import { listCustomerQuotationRelations } from '@/features/crm/quotations/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { getQueryClient } from '@/lib/query-client';

type PageProps = {
  params: Promise<{ id: string }>;
};

export default async function CustomerDetailRoute({ params }: PageProps) {
  const { id } = await params;
  const session = await auth();
  const canRead =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmCustomerRead)));
  const canUpdate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmCustomerUpdate)));
  const canContactCreate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmContactCreate)));
  const canContactRead =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmContactRead)));
  const canContactUpdate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmContactUpdate)));
  const canContactDelete =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmContactDelete)));
  const queryClient = getQueryClient();

  if (canRead) {
    void queryClient.prefetchQuery(customerByIdOptions(id));
  }

  if (canContactRead) {
    void queryClient.prefetchQuery(customerContactsOptions(id));
  }

  const referenceData =
    canRead && session?.user?.activeOrganizationId
      ? await getCustomerReferenceData(session.user.activeOrganizationId)
      : null;
  const relatedEnquiries =
    canRead && session?.user?.activeOrganizationId
      ? await listCustomerEnquiryRelations(id, session.user.activeOrganizationId)
      : [];
  const relatedQuotations =
    canRead && session?.user?.activeOrganizationId
      ? await listCustomerQuotationRelations(id, session.user.activeOrganizationId)
      : [];

  return (
    <PageContainer
      pageTitle='Customer Detail'
      pageDescription='Customer profile, contacts, audit timeline, and future CRM document handoff.'
      access={canRead}
      accessFallback={
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          You do not have access to this customer record.
        </div>
      }
    >
      {referenceData ? (
        <HydrationBoundary state={dehydrate(queryClient)}>
          <CustomerDetail
            customerId={id}
            referenceData={referenceData}
            canUpdate={canUpdate}
            canReadContacts={canContactRead}
            canManageContacts={{
              create: canContactCreate,
              update: canContactUpdate,
              delete: canContactDelete
            }}
            relatedEnquiries={relatedEnquiries}
            relatedQuotations={relatedQuotations}
          />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}
