package com.mvrent.carrental.controller;

import com.mvrent.carrental.model.User;
import com.mvrent.carrental.service.ReviewService;
import com.mvrent.carrental.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/** Customer-facing endpoint for leaving a car review. */
@Controller
@RequiredArgsConstructor
public class ReviewController {

    private final ReviewService reviewService;
    private final UserService userService;

    @PostMapping("/reviews")
    public String submit(@RequestParam Long carId,
                         @RequestParam(required = false) Long bookingId,
                         @RequestParam int rating,
                         @RequestParam(required = false) String comment,
                         @AuthenticationPrincipal UserDetails principal,
                         RedirectAttributes ra) {
        try {
            User user = userService.findByUsername(principal.getUsername());
            reviewService.addReview(user, carId, bookingId, rating, comment);
            ra.addFlashAttribute("reviewSuccess", "Thanks! Your review has been posted.");
        } catch (RuntimeException ex) {
            ra.addFlashAttribute("reviewError", ex.getMessage());
        }
        return "redirect:/cars/" + carId;
    }
}
