import { prisma } from "@/lib/db";

export async function getDashboardStats() {
  const now = new Date();
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());

  const [
    projectCount,
    commitCount,
    deploysTotal,
    deploysToday,
    deployFailures,
    lastSuccess,
  ] = await Promise.all([
    prisma.project.count(),
    prisma.commitLog.count(),
    prisma.deployHistory.count(),
    prisma.deployHistory.count({ where: { startedAt: { gte: todayStart } } }),
    prisma.deployHistory.count({ where: { status: "failed" } }),
    prisma.deployHistory.findFirst({
      where: { status: "success" },
      orderBy: { finishedAt: "desc" },
      include: { project: { select: { name: true } } },
    }),
  ]);

  return {
    projectCount,
    commitCount,
    deploysTotal,
    deploysToday,
    deployFailures,
    lastSuccessAt: lastSuccess?.finishedAt ?? null,
    lastSuccessProject: lastSuccess?.project.name ?? null,
  };
}
