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

const router = Router();

// GET /api/admin/payments - All payments
router.get('/', requireAdmin, async (req, res, next) => {
  try {
    const { page = '1', pageSize = '20', type, status } = req.query;
    const skip = (parseInt(page as string) - 1) * parseInt(pageSize as string);
    const take = parseInt(pageSize as string);

    const where: any = {};
    if (type) where.type = type;
    if (status) where.status = status;

    const [payments, total] = await Promise.all([
      prisma.payment.findMany({
        where,
        include: {
          user: { select: { id: true, fullName: true, avatar: true } },
          listing: { select: { id: true, title: true } },
        },
        skip,
        take,
        orderBy: { createdAt: 'desc' },
      }),
      prisma.payment.count({ where }),
    ]);

    res.json({
      data: payments,
      total,
      page: parseInt(page as string),
      pageSize: take,
      totalPages: Math.ceil(total / take),
    });
  } catch (error) {
    next(error);
  }
});

// GET /api/admin/payments/revenue - Revenue breakdown
router.get('/revenue', requireAdmin, async (_req, res, next) => {
  try {
    const [listingFees, commissions, promotions, subscriptions] = await Promise.all([
      prisma.payment.aggregate({ where: { type: 'LISTING_FEE', status: 'COMPLETED' }, _sum: { amount: true }, _count: true }),
      prisma.payment.aggregate({ where: { type: 'COMMISSION', status: 'COMPLETED' }, _sum: { amount: true }, _count: true }),
      prisma.payment.aggregate({ where: { type: 'PROMOTION', status: 'COMPLETED' }, _sum: { amount: true }, _count: true }),
      prisma.payment.aggregate({ where: { type: 'SUBSCRIPTION', status: 'COMPLETED' }, _sum: { amount: true }, _count: true }),
    ]);

    res.json({
      listingFees: { total: listingFees._sum.amount || 0, count: listingFees._count },
      commissions: { total: commissions._sum.amount || 0, count: commissions._count },
      promotions: { total: promotions._sum.amount || 0, count: promotions._count },
      subscriptions: { total: subscriptions._sum.amount || 0, count: subscriptions._count },
    });
  } catch (error) {
    next(error);
  }
});

export default router;
