package com.yaoyuan.jiscuss.controller.api;

import com.yaoyuan.jiscuss.controller.BaseController;
import com.yaoyuan.jiscuss.entity.UserInfo;
import com.yaoyuan.jiscuss.response.ApiResponse;
import com.yaoyuan.jiscuss.service.ILikeCollectService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * REST API for voting (like / dislike) on discussions and posts.
 */
@Tag(name = "Vote API", description = "Like and dislike discussions and posts")
@RestController
@RequestMapping("/api")
public class VoteController extends BaseController {

    @Autowired
    private ILikeCollectService likeCollectService;

    @Operation(summary = "Vote on a discussion")
    @PostMapping("/discussions/{id}/vote")
    public ApiResponse<Map<String, String>> voteDiscussion(
            @PathVariable Integer id,
            @RequestParam String action,
            HttpServletRequest request) {
        UserInfo user = getUserInfo(request);
        if (user == null) {
            return ApiResponse.fail(401, "请先登录");
        }
        if (!"like".equals(action) && !"dislike".equals(action)) {
            return ApiResponse.fail(400, "action 参数必须是 like 或 dislike");
        }
        String result = likeCollectService.voteDiscussion(user.getId(), id, action);
        return ApiResponse.ok(Map.of("action", result));
    }

    @Operation(summary = "Vote on a post (reply)")
    @PostMapping("/posts/{id}/vote")
    public ApiResponse<Map<String, String>> votePost(
            @PathVariable Integer id,
            @RequestParam String action,
            HttpServletRequest request) {
        UserInfo user = getUserInfo(request);
        if (user == null) {
            return ApiResponse.fail(401, "请先登录");
        }
        if (!"like".equals(action) && !"dislike".equals(action)) {
            return ApiResponse.fail(400, "action 参数必须是 like 或 dislike");
        }
        String result = likeCollectService.votePost(user.getId(), id, action);
        return ApiResponse.ok(Map.of("action", result));
    }
}
