import { Router } from 'express';
import { prisma } from '../../config/database.js';
import { requireModerator, requireAdmin } from '../../middleware/requireRole.js';

const router = Router();

// GET /api/admin/stats - General stats
router.get('/', requireModerator, async (_req, res, next) => {
  try {
    const [totalUsers, totalListings, activeListings, pendingListings, totalOffers, totalPayments, activeToday] = await Promise.all([
      prisma.user.count(),
      prisma.listing.count(),
      prisma.listing.count({ where: { status: 'ACTIVE' } }),
      prisma.listing.count({ where: { status: 'PENDING_REVIEW' } }),
      prisma.offer.count(),
      prisma.payment.aggregate({ where: { status: 'COMPLETED' }, _sum: { amount: true } }),
      prisma.user.count({ where: { updatedAt: { gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } } }),
    ]);

    res.json({
      totalUsers,
      totalListings,
      activeListings,
      pendingListings,
      totalOffers,
      totalRevenue: totalPayments._sum.amount || 0,
      activeToday,
    });
  } catch (error) {
    next(error);
  }
});

// GET /api/admin/stats/revenue - Revenue over time
router.get('/revenue', requireAdmin, async (req, res, next) => {
  try {
    const { period = 'daily' } = req.query;
    const days = period === 'monthly' ? 365 : period === 'weekly' ? 90 : 30;
    const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);

    const payments = await prisma.payment.findMany({
      where: { status: 'COMPLETED', createdAt: { gte: since } },
      select: { amount: true, type: true, createdAt: true },
      orderBy: { createdAt: 'asc' },
    });

    res.json(payments);
  } catch (error) {
    next(error);
  }
});

// GET /api/admin/stats/users - User growth
router.get('/users', requireAdmin, async (_req, res, next) => {
  try {
    const since = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
    const users = await prisma.user.findMany({
      where: { createdAt: { gte: since } },
      select: { createdAt: true },
      orderBy: { createdAt: 'asc' },
    });
    res.json(users);
  } catch (error) {
    next(error);
  }
});

// GET /api/admin/stats/listings - Listing activity
router.get('/listings', requireModerator, async (_req, res, next) => {
  try {
    const since = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const listings = await prisma.listing.findMany({
      where: { createdAt: { gte: since } },
      select: { createdAt: true, status: true },
      orderBy: { createdAt: 'asc' },
    });
    res.json(listings);
  } catch (error) {
    next(error);
  }
});

export default router;
