package com.emotion.controller;

import com.emotion.common.PageResult;
import com.emotion.common.Result;
import com.emotion.dto.request.comment.CommentCreateRequest;
import com.emotion.dto.request.comment.CommentUpdateRequest;
import com.emotion.dto.request.comment.CommentPageRequest;
import com.emotion.dto.response.comment.CommentResponse;
import com.emotion.service.CommentService;
import com.emotion.util.UserContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 评论控制器
 * 
 * @author huazhongmin
 * @date 2025-07-23
 */
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    /**
     * 分页查询评论
     */
    @GetMapping(value = "/page")
    public Result<PageResult<CommentResponse>> getCommentPage(@Validated CommentPageRequest request) {
        PageResult<CommentResponse> pageResult = commentService.getPage(request);
        return Result.success(pageResult);
    }

    /**
     * 创建评论
     */
    @PostMapping(value = "/create")
    public Result<CommentResponse> createComment(@RequestBody @Validated CommentCreateRequest request) {
        // 从上下文中获取当前用户ID，而不是直接使用请求中的用户ID
        String currentUserId = UserContextUtils.getCurrentUserId();
        if (currentUserId != null) {
            request.setUserId(currentUserId);
        }
        CommentResponse response = commentService.create(request);
        return Result.success(response);
    }

    /**
     * 更新评论
     */
    @PutMapping(value = "/update")
    public Result<CommentResponse> updateComment(@RequestBody @Validated CommentUpdateRequest request) {
        CommentResponse response = commentService.update(request);
        return Result.success(response);
    }

    /**
     * 删除评论
     */
    @DeleteMapping(value = "/delete")
    public Result<Void> deleteComment(@RequestParam String id) {
        boolean deleted = commentService.delete(id);
        if (!deleted) {
            return Result.error("删除失败");
        }
        return Result.success();
    }

    /**
     * 根据ID获取评论
     */
    @GetMapping(value = "/detail")
    public Result<CommentResponse> getCommentById(@RequestParam String id) {
        CommentResponse response = commentService.getById(id);
        if (response == null) {
            return Result.notFound("评论不存在");
        }
        return Result.success(response);
    }
}