package com.sonic.frog.controller.web;

import com.sonic.common.auth.domains.Session;
import com.sonic.common.rpc.Result;
import com.sonic.common.utils.RedisLock;
import com.sonic.frog.domain.input.CreateEditAiUserInput;
import com.sonic.frog.domain.input.DelAiUserInput;
import com.sonic.frog.domain.input.EditAiHeadImgInput;
import com.sonic.frog.domain.input.GetAiUserInfoInput;
import com.sonic.frog.domain.output.AiUserInfoOutput;
import com.sonic.frog.domain.output.CreateEditAiUserOutput;
import com.sonic.frog.service.AiUserSetService;
import com.sonic.frog.utils.RedisKeyUtils;
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.*;

import javax.validation.Valid;

/**
 * Web-AI用户设置
 *
 * @author: mzc
 * @date: 2025-07-11 11:43
 **/
@RestController
@Slf4j
public class AiUserSetWeb {

    @Autowired
    private RedisLock.RedisWrapper redisWrapper;
    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private AiUserSetService aiUserSetService;

    @ApiOperation(value = "创建或编辑AI", tags = {"Web-AI用户设置"})
    @PostMapping("/web/ai-user/create-edit")
    public Result createEditAiUser(@Valid @Validated @RequestBody CreateEditAiUserInput input, @ApiParam(hidden = true) Session session) {
        //redis键
        String aiUserCreateEditLockKey = redisKeyUtils.aiUserCreateEditLockKey(session.getUserId());
        //加锁处理
        RedisLock redisLock = new RedisLock(aiUserCreateEditLockKey, redisWrapper);
        CreateEditAiUserOutput output = redisLock.tryAcquireRun(() -> {
            return aiUserSetService.createEditAiUser(input, session.getUserId());
        });
        return Result.success(output);
    }

    @ApiOperation(value = "删除AI用户", tags = {"Web-AI用户设置"})
    @PostMapping("/web/ai-user/del")
    public Result delAiUser(@Valid @RequestBody DelAiUserInput input, @ApiParam(hidden = true) Session session) {
        aiUserSetService.delAiUser(input.getAiId(), session.getUserId());
        return Result.success();
    }

    @ApiOperation(value = "获取AI信息", tags = {"Web-AI用户设置"})
    @PostMapping("/web/ai-user/get-my-ai-user/info")
    public Result<AiUserInfoOutput> getMyAiUserInfo(@Valid @RequestBody GetAiUserInfoInput input, @ApiParam(hidden = true) Session session) {
        return Result.success(aiUserSetService.getMyAiUserInfo(input.getAiId(), session.getUserId()));
    }

    @ApiOperation(value = "修改AI头像", tags = {"WEB-AI用户设置"})
    @RequestMapping(value = "/web/ai-user/edit-head-img", produces = {"application/json"}, method = RequestMethod.POST)
    public Result<Void> editAiHeadImg(@Valid @RequestBody EditAiHeadImgInput input,@ApiParam(hidden = true) Session session) {
        aiUserSetService.editAiHeadImg(session.getUserId(), input);
        return Result.success();
    }

}
