import { notFound } from "next/navigation"
import { prisma } from "@/lib/prisma"
import ClientDetails from "./ClientDetails"

type Props = {
  params: Promise<{ id: string }>
}

export default async function ClientPage({ params }: Props) {
  const { id } = await params

  const client = (await prisma.client.findUnique({
    where: { id },
    include: {
      invoices: {
        include: {
          seller: true,
          items: {
            include: {
              product: true
            }
          }
        },
        orderBy: { createdAt: 'desc' }
      },
      prescriptions: {
        include: {
          products: true,
          visions: true
        },
        orderBy: { createdAt: 'desc' }
      },
      appointments: {
        orderBy: { date: 'desc' }
      }
    }
  })) as any

  if (!client) {
    notFound()
  }

  const totalPurchases = client.invoices.reduce((sum: number, inv: any) => sum + Number(inv.total), 0)
  const invoiceCount = client.invoices.length

  const clientWithStats = {
    ...client,
    totalPurchases,
    invoiceCount
  }

  return <ClientDetails client={clientWithStats} />
}
