package com.sonic.bear.controller.mock;

import com.sonic.common.AppRuntime;
import com.sonic.common.auth.domains.Session;
import com.sonic.common.rpc.Result;
import com.sonic.common.utils.RedisLock;
import com.sonic.sdk.api.annotation.IgnoreAuth;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author: code
 * @date: 2025/06/01
 * @Description:
 * @version: 1.0.0
 */
@Slf4j
@RestController
public class MockController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisLock.RedisWrapper redisWrapper;
    @Autowired
    private AppRuntime appRuntime;
    @Autowired
    private RedisTemplate redisTemplate;

    @IgnoreAuth
    @ApiOperation(value = "redis连接测试", tags = "lion-冒烟")
    @PostMapping("/mock/redis/test/set-get")
    public Result<String> testSetGet(Session session) {
        String key = "aaa:111";
        stringRedisTemplate.opsForValue().set(key, "上海", 3, TimeUnit.MINUTES);
        return Result.success(stringRedisTemplate.opsForValue().get(key));
    }

    @IgnoreAuth
    @ApiOperation(value = "redis连接测试", tags = "lion-冒烟")
    @PostMapping("/mock/redis/test/exp")
    public Result<String> exp(Session session) {
        String key = "aaa:111";
        return Result.success(stringRedisTemplate.getExpire(key));
    }

    @IgnoreAuth
    @ApiOperation(value = "redis加锁测试", tags = "lion-冒烟")
    @PostMapping("/mock/redis/test/lock-v1")
    public Result<String> lockV1(Session session) {
        String key = "aaa:333";
        //加锁，避免定时任务并发重复处理
        RedisLock redisLock = new RedisLock(key, redisWrapper);
        redisLock.tryAcquireRun(10 * 60 * 1000, () -> {
            System.out.println("=====> redis加锁测试 通过");
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return true;
        });
        return Result.success("V1 成功");
    }


}
