import { Router } from 'express';
import { prisma } from '../config/database.js';
import { authenticate } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import { createReviewSchema, respondReviewSchema } from '../validators/rental-review.js';
import { AppError } from '../middleware/errorHandler.js';

const router = Router();

// --- Create review (tenant only, on completed booking) ---
router.post('/', authenticate, validate(createReviewSchema), async (req, res, next) => {
  try {
    const { bookingId, rating, comment } = req.body;

    const booking = await prisma.booking.findUnique({
      where: { id: bookingId },
      include: { review: true },
    });
    if (!booking) throw new AppError(404, 'Booking not found');
    if (booking.tenantId !== req.userId) throw new AppError(403, 'Not authorized');
    if (booking.status !== 'COMPLETED') throw new AppError(400, 'Can only review completed bookings');
    if (booking.review) throw new AppError(409, 'Review already exists for this booking');

    const review = await prisma.rentalReview.create({
      data: {
        bookingId,
        rentalListingId: booking.rentalListingId,
        tenantId: req.userId!,
        landlordId: booking.landlordId,
        rating,
        comment,
      },
      include: {
        tenant: { select: { id: true, fullName: true, avatar: true } },
      },
    });

    // Notify landlord
    const notification = await prisma.notification.create({
      data: {
        userId: booking.landlordId,
        type: 'RENTAL_REVIEW',
        title: 'New Review',
        body: `You received a ${rating}-star review`,
        data: { reviewId: review.id, bookingId },
      },
    });

    const io = req.app.get('io');
    if (io) {
      io.to(`user:${booking.landlordId}`).emit('new_notification', notification);
    }

    res.status(201).json(review);
  } catch (error) {
    next(error);
  }
});

// --- Landlord respond to review ---
router.patch('/:id/respond', authenticate, validate(respondReviewSchema), async (req, res, next) => {
  try {
    const review = await prisma.rentalReview.findUnique({ where: { id: req.params.id } });
    if (!review) throw new AppError(404, 'Review not found');
    if (review.landlordId !== req.userId) throw new AppError(403, 'Not authorized');

    const updated = await prisma.rentalReview.update({
      where: { id: req.params.id },
      data: { landlordResponse: req.body.response },
      include: {
        tenant: { select: { id: true, fullName: true, avatar: true } },
      },
    });

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

// --- Get all reviews for a landlord ---
router.get('/landlord/:id', async (req, res, next) => {
  try {
    const reviews = await prisma.rentalReview.findMany({
      where: { landlordId: req.params.id },
      include: {
        tenant: { select: { id: true, fullName: true, avatar: true } },
        rentalListing: { select: { id: true, title: true } },
      },
      orderBy: { createdAt: 'desc' },
    });

    const avgRating = reviews.length > 0
      ? reviews.reduce((sum, r) => sum + r.rating, 0) / reviews.length
      : 0;

    res.json({ reviews, avgRating, totalReviews: reviews.length });
  } catch (error) {
    next(error);
  }
});

export default router;
