package com.ruoyi.novel.controller;
//# 广告计数接口

import com.ruoyi.novel.domain.AdCountRequest;
import com.ruoyi.novel.service.AdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/ad")
public class NovelAdController {

    private final AdService adService;
    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public NovelAdController(AdService adService, RedisTemplate<String, String> redisTemplate) {
        this.adService = adService;
        this.redisTemplate = redisTemplate;
    }

    @PostMapping("/count")
    public ResponseEntity<?> countAdView(
            @RequestBody AdCountRequest request,
            @RequestHeader(value = "X-PHP-Session", required = false) String phpSessionId
    ) {
        // 验证请求来源
        if (!isValidSource(request.getSource())) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Invalid source");
        }

        // 会话同步处理
        String userId = resolveUserId(request, phpSessionId);

        // 防重处理 (5分钟内同一章节只计数一次)
        String redisKey = String.format("ad:%s:%s:%s",
                request.getSource(), userId, request.getChapterId());

        if (redisTemplate.hasKey(redisKey)) {
            return ResponseEntity.ok("Already counted");
        }

        // 记录广告
        adService.logAdView(
                userId,
                request.getChapterId(),
                request.getAdType(),
                request.getSource()
        );

        // 设置Redis锁
        redisTemplate.opsForValue().set(redisKey, "1", Duration.ofMinutes(5));

        return ResponseEntity.ok("Ad counted");
    }

    private String resolveUserId(AdCountRequest request, String phpSessionId) {
        // 优先使用PHP会话
        if (phpSessionId != null) {
            String sessionKey = "session:" + phpSessionId;
            String userId = redisTemplate.opsForValue().get(sessionKey + ":user_id");
            if (userId != null) return userId;
        }

        // 其次使用请求中的用户ID
        if (request.getUserId() != null) {
            return request.getUserId().toString();
        }

        // 最后使用设备ID
        return request.getDeviceId();
    }

    private boolean isValidSource(String source) {
        List<String> validSources = Arrays.asList("h5", "wechat", "douyin", "app");
        return validSources.contains(source);
    }
}