package com.example.system.controller;

import com.example.system.model.CommentTable;
import com.example.system.model.Result;
import com.example.system.repository.CommentRepository;
import com.example.system.service.CommpentService;
import com.example.system.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Objects;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private CommpentService commpentService;

    // 根据文章id获取所有评论
    @GetMapping("/getAllById")
    public Object getAllCommentsById(Integer id) {
        log.info("根据文章id获取所有评论 id: {}", id);
        if (id <= 0) {
            return Result.fail("非法id");
        }
        return commpentService.getCommentById(id);
    }

    // 发布评论
    @PostMapping("/creat")
    public ResponseEntity<CommentTable> addComment(CommentTable comment) {
        log.info("发布评论 comment: {}", comment);
        comment.setPublishTime(new Date(System.currentTimeMillis()));
        CommentTable savedComment = commentRepository.save(comment);
        return ResponseEntity.ok().body(savedComment);
    }

    // 删除评论
    @DeleteMapping("/delete/{id}")
    public Object deleteComment(@PathVariable Long id, HttpServletRequest request) {
        log.info("删除评论 id: {}", id);
        String toKen =request.getHeader("Authorization");
        Claims claims = JWTUtil.checkToken(toKen);
        Integer userPrivileges = (Integer) claims.get("userPrivileges");
        if (userPrivileges == 2) {
            Integer userId = (Integer) claims.get("userId");
            //根据评论id找到对应的评论
            CommentTable comment = commpentService.getById(id);
            if (!Objects.equals(comment.getUserId(), userId)) {
                return Result.fail("不能删除别人的评论");
            }
        }
        return commpentService.deleteById(id);
    }
}