import { Router } from "express";
import { requests } from "../lib/mockDb.js";

const router = Router();

router.get("/stats", (_req, res) => {
  const totalRequests = requests.length;
  const totalDonated = requests.filter((r) =>
    ["donated", "delivered", "receipt_confirmed", "thank_you_submitted", "whatsapp_sent", "closed"].includes(r.status)
  ).length;
  const totalCollected = requests.reduce((sum, r) => sum + r.collectedAmount, 0);
  const totalClosed = requests.filter((r) => r.status === "closed").length;
  const pendingVerification = requests.filter((r) =>
    ["new", "pending_review"].includes(r.status)
  ).length;
  const activeOpportunities = requests.filter((r) => r.status === "published").length;

  const statusCounts: Record<string, number> = {};
  for (const r of requests) {
    statusCounts[r.status] = (statusCounts[r.status] || 0) + 1;
  }
  const byStatus = Object.entries(statusCounts).map(([status, count]) => ({
    status,
    count,
  }));

  const needTypeCounts: Record<string, { count: number; totalAmount: number }> = {};
  for (const r of requests) {
    if (!needTypeCounts[r.needType]) {
      needTypeCounts[r.needType] = { count: 0, totalAmount: 0 };
    }
    needTypeCounts[r.needType].count += 1;
    needTypeCounts[r.needType].totalAmount += r.requestedAmount;
  }
  const byNeedType = Object.entries(needTypeCounts).map(([needType, v]) => ({
    needType,
    count: v.count,
    totalAmount: v.totalAmount,
  }));

  res.json({
    totalRequests,
    totalDonated,
    totalCollected,
    totalClosed,
    pendingVerification,
    activeOpportunities,
    byStatus,
    byNeedType,
  });
});

export default router;
