import { Router, Response, NextFunction } from 'express';
import prisma from '../lib/prisma';
import { AuthRequest } from '../middleware/auth';

const router = Router();

// GET /api/stats — public dashboard stats
router.get('/', async (_req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const [
      burrowCount,
      activeBurrows,
      sightingCount,
      verifiedSightings,
      volunteerCount,
      totalHoursResult,
      donationResult,
      upcomingEvents,
      liveStreams,
    ] = await Promise.all([
      prisma.burrow.count(),
      prisma.burrow.count({ where: { status: 'active' } }),
      prisma.wildlifeSighting.count(),
      prisma.wildlifeSighting.count({ where: { verified: true } }),
      prisma.user.count({ where: { role: 'volunteer' } }),
      prisma.volunteerHour.aggregate({ _sum: { hours: true } }),
      prisma.donation.aggregate({ _sum: { amount: true }, _count: true }),
      prisma.event.count({ where: { date: { gte: new Date() } } }),
      prisma.livestreamSource.count({ where: { status: 'live' } }),
    ]);

    res.json({
      burrows: {
        total: burrowCount,
        active: activeBurrows,
        inactive: burrowCount - activeBurrows,
      },
      wildlife: {
        total_sightings: sightingCount,
        verified: verifiedSightings,
      },
      volunteers: {
        count: volunteerCount,
        total_hours: totalHoursResult._sum.hours ?? 0,
      },
      donations: {
        total_amount: donationResult._sum.amount ?? 0,
        total_count: donationResult._count,
      },
      events: {
        upcoming: upcomingEvents,
      },
      streams: {
        live: liveStreams,
      },
    });
  } catch (err) { next(err); }
});

export default router;
