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

const router = Router();

// --- List all bookings ---
router.get('/', requireModerator, async (req, res, next) => {
  try {
    const { page = '1', pageSize = '20', status } = req.query;
    const skip = (parseInt(page as string) - 1) * parseInt(pageSize as string);
    const take = parseInt(pageSize as string);

    const where: Record<string, unknown> = {};
    if (status) where.status = status;

    const [data, total] = await Promise.all([
      prisma.booking.findMany({
        where,
        include: {
          rentalListing: { select: { id: true, title: true, category: true, location: true, cancellationPolicy: true, images: { take: 1, orderBy: { order: 'asc' as const } } } },
          tenant: { select: { id: true, fullName: true, email: true } },
          landlord: { select: { id: true, fullName: true, email: true } },
          payout: true,
        },
        skip, take,
        orderBy: { createdAt: 'desc' },
      }),
      prisma.booking.count({ where }),
    ]);

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

export default router;
