package de.itsolutions.ticketsystem.controller; import de.itsolutions.ticketsystem.entity.Comment; import de.itsolutions.ticketsystem.entity.Ticket; import de.itsolutions.ticketsystem.entity.User; import de.itsolutions.ticketsystem.repository.CommentRepository; import de.itsolutions.ticketsystem.repository.TicketRepository; import de.itsolutions.ticketsystem.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import java.util.List; import java.util.Map; /** * REST controller for managing comments on tickets. */ @RestController @RequestMapping("/api/tickets/{ticketId}/comments") public class CommentController { @Autowired private CommentRepository commentRepository; @Autowired private TicketRepository ticketRepository; @Autowired private UserRepository userRepository; /** * Retrieves all comments for a specific ticket. * @param ticketId The ID of the ticket. * @return A list of comments for the specified ticket. * @throws ResponseStatusException if the ticket is not found. */ @GetMapping public List getComments(@PathVariable Long ticketId) { if (!ticketRepository.existsById(ticketId)) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Ticket not found"); } return commentRepository.findByTicketIdOrderByCreatedAtAsc(ticketId); } /** * Adds a new comment to a ticket. * @param ticketId The ID of the ticket to add the comment to. * @param payload A map containing the comment text. * @return The newly created comment. * @throws ResponseStatusException if the text is empty, ticket is not found, or user is not found. */ @PostMapping public Comment addComment(@PathVariable Long ticketId, @RequestBody Map payload) { String text = payload.get("text"); if (text == null || text.trim().isEmpty()) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Text is required"); } Ticket ticket = ticketRepository.findById(ticketId) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Ticket not found")); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String email = auth.getName(); User user = userRepository.findByEmail(email) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found")); Comment comment = new Comment(); comment.setText(text); comment.setTicket(ticket); comment.setAuthor(user); return commentRepository.save(comment); } }