package com.sonic.frog.controller.web;

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.frog.domain.entity.Liked;
import com.sonic.frog.domain.input.AiUserLikeOrCancelInput;
import com.sonic.frog.domain.input.AiUserStatInput;
import com.sonic.frog.domain.input.LikeOrCancelPicInput;
import com.sonic.frog.domain.output.AiUserStatOutput;
import com.sonic.frog.limit.RequestLimit;
import com.sonic.frog.service.AiUserStatService;
import com.sonic.frog.service.LikedService;
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;

import javax.servlet.http.HttpServletRequest;

/**
 * Web-点赞
 *
 * @author code
 */
@RestController
@Slf4j
public class LikedWeb {

    @Autowired
    private AppRuntime appRuntime;
    @Autowired
    private RedisLock.RedisWrapper redisWrapper;
    @Autowired
    private LikedService likedService;

    @RequestLimit(count = 30, loginCount = 40, message = "operate too frequently，please try again later (101) ")
    @ApiOperation(value = "ai用户点赞、取消点赞", tags = {"WEB-点赞"})
    @PostMapping(value = "/web/ai-user/like-or-cancel")
    public Result<Void> likeOrCancel(@Validated @RequestBody AiUserLikeOrCancelInput input, @ApiParam(hidden = true) Session session, @ApiParam(hidden = true)  HttpServletRequest request) {
        //操作人加锁，防止并发操作
        RedisLock redisLock = new RedisLock(appRuntime.buildPrefixKey(Liked.BizType.AI.name(), "liked", session.getUserId(), input.getAiId()), redisWrapper);
        redisLock.tryAcquireRun(() -> {
            likedService.aiUserLikeOrCancel(session.getUserId(), input);
            return true;
        });
        return Result.success();
    }

}
