package com.ruoyi.novel.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//# 剧情投票接口
// NovelVoteController.java
@RestController
@RequestMapping("/story/vote")
public class NovelVoteController {

    @Autowired
    private IVoteService voteService;

    // 使用Guava RateLimiter限制投票频率
    private static final ConcurrentHashMap<Long, RateLimiter> userRateLimiters = new ConcurrentHashMap<>();
    private static final int MAX_VOTES_PER_DAY = 3;

    @PostMapping("/next")
    public AjaxResult voteForStoryBranch(@RequestBody VoteRequest request) {
        // 1. 频率限制检查
        RateLimiter rateLimiter = userRateLimiters.computeIfAbsent(
                request.getUserId(),
                k -> RateLimiter.create(MAX_VOTES_PER_DAY)
        );

        if (!rateLimiter.tryAcquire()) {
            return AjaxResult.error("Exceeded daily vote limit");
        }

        // 2. 调用DeepSeek API生成剧情
        String generatedContent = voteService.generateStoryContent(
                request.getStoryId(),
                request.getOptionId()
        );

        // 3. 异步通知PHP系统
        voteService.notifyPhpSystem(request, generatedContent);

        return AjaxResult.success("Vote processed", generatedContent);
    }
}
