import { auth } from '@/auth';
import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import PageContainer from '@/components/layout/page-container';
import { leadByIdOptions } from '@/features/crm/leads/api/queries';
import { LeadDetail } from '@/features/crm/leads/components/lead-detail';
import { getLeadReferenceData } from '@/features/crm/leads/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { getQueryClient } from '@/lib/query-client';

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

export default async function LeadDetailRoute({ 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.crmLeadRead)));

  const canUpdate =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmLeadUpdate)));

  const canDelete =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmLeadDelete)));

  const canAssign =
    session?.user?.systemRole === 'super_admin' ||
    (!!session?.user?.activeOrganizationId &&
      (session.user.activeMembershipRole === 'admin' ||
        session.user.activePermissions.includes(PERMISSIONS.crmLeadAssign)));

  if (!canRead || !session?.user?.activeOrganizationId) {
    return (
      <PageContainer access={false} pageTitle='Lead Detail'>
        {null}
      </PageContainer>
    );
  }

  const queryClient = getQueryClient();
  await queryClient.prefetchQuery(leadByIdOptions(id));
  const referenceData = await getLeadReferenceData(session.user.activeOrganizationId);

  return (
    <PageContainer
      pageTitle='Lead Detail'
      pageDescription='Separated lead workspace for marketing qualification and sales handoff.'
    >
      <HydrationBoundary state={dehydrate(queryClient)}>
        <LeadDetail
          leadId={id}
          referenceData={referenceData}
          canUpdate={canUpdate}
          canDelete={canDelete}
          canAssign={canAssign}
        />
      </HydrationBoundary>
    </PageContainer>
  );
}
