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

const router = Router();

// GET /api/admin/moderation/queue - Pending review listings
router.get('/queue', requireModerator, async (req, res, next) => {
  try {
    const { page = '1', pageSize = '20' } = req.query;
    const skip = (parseInt(page as string) - 1) * parseInt(pageSize as string);
    const take = parseInt(pageSize as string);

    const [listings, total] = await Promise.all([
      prisma.listing.findMany({
        where: { status: 'PENDING_REVIEW' },
        select: {
          id: true, title: true, description: true, price: true, category: true,
          condition: true, location: true, createdAt: true,
          seller: { select: { id: true, fullName: true, avatar: true, email: true } },
          images: { orderBy: { order: 'asc' } },
        },
        skip,
        take,
        orderBy: { createdAt: 'asc' },
      }),
      prisma.listing.count({ where: { status: 'PENDING_REVIEW' } }),
    ]);

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

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

    const [logs, total] = await Promise.all([
      prisma.moderationLog.findMany({
        include: {
          moderator: { select: { id: true, fullName: true, avatar: true } },
        },
        skip,
        take,
        orderBy: { createdAt: 'desc' },
      }),
      prisma.moderationLog.count(),
    ]);

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

export default router;
