package com.mvrent.carrental.service;

import com.mvrent.carrental.model.Booking;
import com.mvrent.carrental.model.Review;
import com.mvrent.carrental.model.User;
import com.mvrent.carrental.repository.BookingRepository;
import com.mvrent.carrental.repository.ReviewRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ReviewService {

    private final ReviewRepository reviewRepository;
    private final CarService carService;
    private final BookingRepository bookingRepository;

    public List<Review> findAll() {
        return reviewRepository.findAllByOrderByCreatedAtDesc();
    }

    public List<Review> approvedForCar(Long carId) {
        return reviewRepository.findByCarIdAndApprovedTrueOrderByCreatedAtDesc(carId);
    }

    /** Average rating rounded to one decimal, or 0 when none. */
    public double averageForCar(Long carId) {
        Double avg = reviewRepository.averageForCar(carId);
        return avg == null ? 0 : Math.round(avg * 10.0) / 10.0;
    }

    public long countForCar(Long carId) {
        return reviewRepository.countApprovedForCar(carId);
    }

    public Review findById(Long id) {
        return reviewRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Review not found: " + id));
    }

    @Transactional
    public Review addReview(User user, Long carId, Long bookingId, int rating, String comment) {
        if (rating < 1 || rating > 5) throw new IllegalArgumentException("Rating must be between 1 and 5");
        Booking booking = null;
        if (bookingId != null) {
            booking = bookingRepository.findById(bookingId).orElse(null);
            if (booking != null && reviewRepository.existsByBookingId(bookingId)) {
                throw new IllegalArgumentException("You have already reviewed this trip");
            }
        }
        Review review = Review.builder()
                .car(carService.findById(carId))
                .user(user)
                .booking(booking)
                .rating(rating)
                .comment(comment != null && comment.isBlank() ? null : comment)
                .approved(true)
                .build();
        return reviewRepository.save(review);
    }

    @Transactional
    public void setApproved(Long id, boolean approved) {
        Review r = findById(id);
        r.setApproved(approved);
        reviewRepository.save(r);
    }

    @Transactional
    public void delete(Long id) {
        reviewRepository.deleteById(id);
    }
}
