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

const router = Router();

// --- List all rentals ---
router.get('/', requireModerator, async (req, res, next) => {
  try {
    const { page = '1', pageSize = '20', status, category, search } = 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;
    if (category) where.category = category;
    if (search) {
      where.OR = [
        { title: { contains: search as string, mode: 'insensitive' } },
        { location: { contains: search as string, mode: 'insensitive' } },
      ];
    }

    const [data, total] = await Promise.all([
      prisma.rentalListing.findMany({
        where,
        select: {
          id: true, title: true, category: true, location: true, status: true,
          dailyPrice: true, monthlyPrice: true, viewCount: true, isFeatured: true, isVerified: true,
          createdAt: true,
          landlord: { select: { id: true, fullName: true, email: true } },
          images: { take: 1, orderBy: { order: 'asc' } },
          _count: { select: { bookings: true, reviews: true } },
        },
        skip, take,
        orderBy: { createdAt: 'desc' },
      }),
      prisma.rentalListing.count({ where }),
    ]);

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

// --- Approve rental ---
router.patch('/:id/approve', requireModerator, async (req, res, next) => {
  try {
    const rental = await prisma.rentalListing.findUnique({ where: { id: req.params.id } });
    if (!rental) throw new AppError(404, 'Rental not found');
    if (rental.status !== 'PENDING_REVIEW') throw new AppError(400, 'Rental is not pending review');

    const updated = await prisma.rentalListing.update({
      where: { id: req.params.id },
      data: { status: 'ACTIVE', reviewedBy: req.userId, reviewedAt: new Date() },
    });

    // Notify landlord
    await prisma.notification.create({
      data: {
        userId: rental.landlordId,
        type: 'LISTING_APPROVED',
        title: 'Rental Approved',
        body: `Your rental "${rental.title}" has been approved and is now live!`,
        data: { rentalListingId: rental.id },
      },
    });

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

// --- Reject rental ---
router.patch('/:id/reject', requireModerator, async (req, res, next) => {
  try {
    const { reason } = req.body;
    const rental = await prisma.rentalListing.findUnique({ where: { id: req.params.id } });
    if (!rental) throw new AppError(404, 'Rental not found');
    if (rental.status !== 'PENDING_REVIEW') throw new AppError(400, 'Rental is not pending review');

    const updated = await prisma.rentalListing.update({
      where: { id: req.params.id },
      data: { status: 'DRAFT', rejectionReason: reason, reviewedBy: req.userId, reviewedAt: new Date() },
    });

    await prisma.notification.create({
      data: {
        userId: rental.landlordId,
        type: 'LISTING_REJECTED',
        title: 'Rental Rejected',
        body: `Your rental "${rental.title}" was rejected. Reason: ${reason || 'Not specified'}`,
        data: { rentalListingId: rental.id },
      },
    });

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

// --- Force delete rental (admin) ---
router.delete('/:id', requireAdmin, async (req, res, next) => {
  try {
    const rental = await prisma.rentalListing.findUnique({ where: { id: req.params.id } });
    if (!rental) throw new AppError(404, 'Rental not found');

    await prisma.rentalListing.update({ where: { id: req.params.id }, data: { status: 'DELETED' } });
    res.json({ message: 'Rental deleted' });
  } catch (error) {
    next(error);
  }
});

// --- Rental stats ---
router.get('/stats', requireModerator, async (req, res, next) => {
  try {
    const [totalRentals, activeRentals, pendingRentals, totalBookings, activeBookings, completedBookings, totalPayouts, pendingPayouts] = await Promise.all([
      prisma.rentalListing.count({ where: { status: { not: 'DELETED' } } }),
      prisma.rentalListing.count({ where: { status: 'ACTIVE' } }),
      prisma.rentalListing.count({ where: { status: 'PENDING_REVIEW' } }),
      prisma.booking.count(),
      prisma.booking.count({ where: { status: { in: ['CONFIRMED', 'ACTIVE'] } } }),
      prisma.booking.count({ where: { status: 'COMPLETED' } }),
      prisma.payout.count(),
      prisma.payout.count({ where: { status: 'PENDING' } }),
    ]);

    const payoutAgg = await prisma.payout.aggregate({
      where: { status: 'COMPLETED' },
      _sum: { commissionAmount: true, netAmount: true },
    });

    res.json({
      totalRentals, activeRentals, pendingRentals,
      totalBookings, activeBookings, completedBookings,
      totalPayouts, pendingPayouts,
      totalRentalRevenue: payoutAgg._sum.commissionAmount || 0,
      totalPaidOut: payoutAgg._sum.netAmount || 0,
    });
  } catch (error) {
    next(error);
  }
});

export default router;
