import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/session";
import prisma from "@/lib/prisma";

export async function GET() {
  const { error } = await requireAdmin();
  if (error) return error;

  const now = new Date();
  const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);

  const [
    totalLeads,
    newLeads,
    convertedLeads,
    leadsByStatus,
    recentLeads,
    leadsThisMonth,
    leadsLastMonth,
  ] = await Promise.all([
    prisma.lead.count(),
    prisma.lead.count({ where: { status: "NEW" } }),
    prisma.lead.count({ where: { status: "CONVERTED" } }),
    prisma.lead.groupBy({
      by: ["status"],
      _count: { status: true },
    }),
    prisma.lead.findMany({
      take: 5,
      orderBy: { createdAt: "desc" },
    }),
    prisma.lead.count({
      where: { createdAt: { gte: thirtyDaysAgo } },
    }),
    prisma.lead.count({
      where: {
        createdAt: {
          gte: new Date(thirtyDaysAgo.getTime() - 30 * 24 * 60 * 60 * 1000),
          lt: thirtyDaysAgo,
        },
      },
    }),
  ]);

  const conversionRate = totalLeads > 0 ? ((convertedLeads / totalLeads) * 100).toFixed(1) : "0";

  return NextResponse.json({
    totalLeads,
    newLeads,
    convertedLeads,
    conversionRate,
    leadsByStatus,
    recentLeads,
    leadsThisMonth,
    leadsLastMonth,
    growth:
      leadsLastMonth > 0
        ? (((leadsThisMonth - leadsLastMonth) / leadsLastMonth) * 100).toFixed(1)
        : "0",
  });
}
