blob: 17dabb3281e1ae56f5fd964908b988297c4bbdf3 [file] [log] [blame]
package com.pt.controller;
import com.pt.constant.Constants;
import com.pt.service.CommentService;
import com.pt.utils.JWTUtils;
import com.pt.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/comment")
@CrossOrigin(origins = "*")
public class CommentController {
@Autowired
private CommentService commentService;
@PostMapping("/add")
public ResponseEntity<?> addComment(
@RequestHeader("token") String token,
@RequestParam("content") String content,
@RequestParam("username") String username,
@RequestParam("postId") int postId
) {
Map<String, Object> ans = new HashMap<>();
if (!JWTUtils.checkToken(token, username, Constants.UserRole.USER)) {
ans.put("result", "Invalid token");
return ResponseEntity.badRequest().body(ans);
}
commentService.addComment(content, username, postId);
ans.put("result", "Comment added successfully");
return ResponseEntity.ok(ans);
}
@DeleteMapping("/delete")
public ResponseEntity<?> deleteComment(
@RequestHeader("token") String token,
@RequestParam("commentId") int commentId,
@RequestParam("username") String username
) {
Map<String, Object> ans = new HashMap<>();
if (!JWTUtils.checkToken(token, username, Constants.UserRole.ADMIN)) {
ans.put("result", "Invalid token");
return ResponseEntity.badRequest().body(ans);
}
commentService.deleteComment(commentId);
ans.put("result", "Comment deleted successfully");
return ResponseEntity.ok(ans);
}
@GetMapping("/get")
public ResponseEntity<?> getComments(
@RequestHeader("token") String token,
@RequestParam("postId") int postId,
@RequestParam("username") String username
) {
Map<String, Object> ans = new HashMap<>();
if(!JWTUtils.checkToken(token, username, Constants.UserRole.USER)) {
ans.put("result", "Invalid token");
return ResponseEntity.badRequest().body(ans);
}
List<Comment> comments = commentService.getCommentsByPostId(postId);
ans.put("result", "Comments retrieved successfully");
ans.put("data", Map.of(
"comments", comments
));
return ResponseEntity.ok(ans);
}
}