// pages/api/Dashboard/Home.js
import prisma from "@/lib/prisma";

function pickAuthToken(req) {
  const raw = req.headers.authorization || "";
  const token = raw.startsWith("Bearer ") ? raw.slice(7) : raw;
  return token.trim();
}

function decimalToString(d) {
  return d === null || d === undefined ? null : String(d);
}

function safeISO(d) {
  return d ? new Date(d).toISOString() : null;
}

export default async function handler(req, res) {
  if (req.method !== "GET") {
    return res.status(405).json({ success: false, message: "Method not allowed" });
  }

  const SERVER_TOKEN = process.env.SECRET_TOKEN || process.env.NEXT_PUBLIC_SECRET_TOKEN;
  if (SERVER_TOKEN) {
    const token = pickAuthToken(req);
    if (!token || token !== SERVER_TOKEN) {
      return res.status(401).json({ success: false, message: "Unauthorized" });
    }
  }

  try {
    const { dateFrom, dateTo, company } = req.query;

    const where = {};

    if (company) where.agency = String(company);

    if (dateFrom || dateTo) {
      where.startdate = {};
      if (dateFrom) where.startdate.gte = new Date(String(dateFrom));
      if (dateTo) where.startdate.lte = new Date(String(dateTo));
    }

    const totalPolicies = await prisma.policy.count({ where });

    const agg = await prisma.policy.aggregate({
      where,
      _sum: { premium: true },
    });

    // ✅ Prisma v6: count by a field (id) instead of _all
    const byProduct = await prisma.policy.groupBy({
      by: ["product"],
      where,
      _count: { id: true },
      _sum: { premium: true },
      orderBy: { _count: { id: "desc" } },
    });

    const recent = await prisma.policy.findMany({
      where,
      take: 10,
      orderBy: [{ startdate: "desc" }, { createdAt: "desc" }],
      select: {
        id: true,
        agency: true,
        startdate: true,
        insured: true,
        policyEndorsementNo: true,
        plate: true,
        product: true,
        premium: true,
        paymentStatus: true,
      },
    });

    return res.status(200).json({
      success: true,
      summary: {
        totalPolicies,
        premiumSum: decimalToString(agg._sum.premium ?? 0),
      },
      products: byProduct.map((x) => ({
        product: x.product || "Tanımsız",
        count: x._count.id, // ✅ changed
        premiumSum: decimalToString(x._sum.premium ?? 0),
      })),
      recent: recent.map((p) => ({
        ...p,
        startdate: safeISO(p.startdate),
        premium: decimalToString(p.premium),
      })),
    });
  } catch (e) {
    console.error(e);
    return res.status(500).json({ success: false, message: "Server error" });
  }
}