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 {
  getCustomerDetail,
  getCustomerReferenceData
} from '@/features/crm/customers/server/service';
import { listCustomerOpportunityRelations } from '@/features/crm/opportunities/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 canOwnerManage =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmCustomerOwnerManage)));
  const canContactShareRead =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmContactShareRead)));
  const canContactShareManage =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmContactShareManage) ||
        session.user.activePermissions.includes(PERMISSIONS.crmContactShareCreate)));
  const accessContext =
    session?.user?.activeOrganizationId && session?.user?.id
      ? {
          organizationId: session.user.activeOrganizationId,
          userId: session.user.id,
          membershipRole: session.user.activeMembershipRole ?? 'user',
          businessRole: session.user.activeBusinessRole ?? 'sales_support',
          permissions: session.user.activePermissions ?? [],
          branchScopeIds: session.user.activeBranchScopeIds ?? [],
          productTypeScopeIds: session.user.activeProductTypeScopeIds ?? [],
          ownershipScope: session.user.activeOwnershipScope ?? 'organization',
          branchScopeMode: 'all',
          productScopeMode: 'all'
        }
      : null;
  const resolvedCanRead =
    canRead && accessContext
      ? await getCustomerDetail(id, session.user.activeOrganizationId!, accessContext)
          .then(() => true)
          .catch(() => false)
      : false;
  const queryClient = getQueryClient();

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

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

  const referenceData =
    resolvedCanRead && session?.user?.activeOrganizationId
      ? await getCustomerReferenceData(session.user.activeOrganizationId)
      : null;
  const relatedOpportunities =
    resolvedCanRead && session?.user?.activeOrganizationId && accessContext
      ? await listCustomerOpportunityRelations(id, session.user.activeOrganizationId, accessContext)
      : [];
  const relatedQuotations =
    resolvedCanRead && session?.user?.activeOrganizationId && accessContext
      ? await listCustomerQuotationRelations(id, session.user.activeOrganizationId, accessContext)
      : [];

  return (
    <PageContainer
      pageTitle='Customer Detail'
      pageDescription='Customer profile, contacts, audit timeline, and future CRM document handoff.'
      access={resolvedCanRead}
      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
            }}
            canReadContactShares={canContactShareRead}
            canManageContactShares={canContactShareManage}
            canManageOwner={canOwnerManage}
            relatedOpportunities={relatedOpportunities}
            relatedQuotations={relatedQuotations}
          />
        </HydrationBoundary>
      ) : null}
    </PageContainer>
  );
}

