package com.sonic.frog.controller.web;

import com.sonic.common.auth.domains.Session;
import com.sonic.common.rpc.Page;
import com.sonic.common.rpc.Result;
import com.sonic.common.utils.RedisLock;
import com.sonic.frog.domain.input.AiUserGiftListInput;
import com.sonic.frog.domain.input.SendGiftInput;
import com.sonic.frog.domain.output.AiUserGiftListOutput;
import com.sonic.frog.service.AiUserGiftService;
import com.sonic.frog.utils.RedisKeyUtils;
import com.sonic.sdk.api.annotation.IgnoreAuth;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Web-AI用户礼物
 *
 * @author code
 */
@RestController
@Slf4j
public class AiUserGiftWeb {

    @Autowired
    private AiUserGiftService aiUserGiftService;
    @Autowired
    private RedisLock.RedisWrapper redisWrapper;
    @Autowired
    private RedisKeyUtils redisKeyUtils;

    @IgnoreAuth
    @ApiOperation(value = "获取用户获得的礼物列表", tags = {"Web-AI用户礼物"})
    @PostMapping("/web/ai-user-gift/list")
    public Result<Page<AiUserGiftListOutput>> getAiUserGiftList(@Validated @RequestBody AiUserGiftListInput input, @ApiParam(hidden = true) Session session) {
        return Result.success(aiUserGiftService.getAiUserGiftList(input));
    }

    @ApiOperation(value = "用户发送礼物", tags = {"Web-AI用户礼物"})
    @PostMapping("/web/ai-user-gift/send")
    public Result<Void> sendGift(@Validated @RequestBody SendGiftInput input, @ApiParam(hidden = true) Session session) {
        //redis键
        String sendGiftLockKey = redisKeyUtils.sendGiftLockKey(session.getUserId());
        //加锁处理
        RedisLock redisLock = new RedisLock(sendGiftLockKey, redisWrapper);
        redisLock.tryAcquireRun(() -> {
            aiUserGiftService.sendGift(session.getUserId(), input);
            return true;
        });
        return Result.success();
    }

}
