import { db } from "@/lib/db";
import { clients, documents } from "@/lib/db/schema";
import { eq, desc, sql } from "drizzle-orm";
import { ClientsPageClient } from "../../_components/ClientsPageClient";

export default async function ClientsPage() {
  const clientRows = await db
    .select({
      id: clients.id,
      name: clients.name,
      email: clients.email,
      createdAt: clients.createdAt,
      docCount: sql<number>`count(${documents.id})::int`,
      lastActivity: sql<Date | null>`max(${documents.sentAt})`,
    })
    .from(clients)
    .leftJoin(documents, eq(documents.clientId, clients.id))
    .groupBy(clients.id, clients.name, clients.email, clients.createdAt)
    .orderBy(desc(clients.createdAt));

  return <ClientsPageClient clients={clientRows} />;
}
