package com.seer.teach.openapi.controller;

import cn.hutool.json.JSONUtil;
import com.seer.teach.common.ResultBean;
import com.seer.teach.common.annotation.LogPrint;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.SignUtils;
import com.seer.teach.openapi.entity.AppKeySecretsEntity;
import com.seer.teach.openapi.entity.SnCodesEntity;
import com.seer.teach.openapi.request.AuthReq;
import com.seer.teach.openapi.resp.ApiAuthResp;
import com.seer.teach.openapi.service.AppKeySecretsService;
import com.seer.teach.openapi.service.SnCodesService;
import com.seer.teach.openapi.uitl.StpOpenApiUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: Captain
 * @Description: Ai批改
 * @Date: 2025-05-12 14:28
 */
@Validated
@RestController
@RequiredArgsConstructor
@Tag(name = "API - 认证")
@RequestMapping("/oauth")
public class AuthController {

    private final SnCodesService snCodesService;

    private final AppKeySecretsService appKeySecretsService;


    @LogPrint
    @Operation(summary = "SN认证")
    @PostMapping("/token")
    public ResultBean<String> token(@RequestBody @Validated AuthReq params) {
        // 1. 根据 SN 获取授权信息
        SnCodesEntity auth = snCodesService.auth(params.getSn());
        AssertUtils.notNull(auth, ResultCodeEnum.API_SN_ERROR);

        // 2. 获取 appKey
        AppKeySecretsEntity appKeys = appKeySecretsService.getById(auth.getAppId());
        AssertUtils.notNull(appKeys, ResultCodeEnum.APPID_NOT_EXIST);
        StpOpenApiUtils.login(auth.getId());
        String token = StpOpenApiUtils.getTokenInfo().getTokenValue();

        // 5. 构建返回对象并加密
        ApiAuthResp apiAuthResp = new ApiAuthResp(token, 7200);
        String encryptedResp = SignUtils.encrypt(JSONUtil.toJsonStr(apiAuthResp), appKeys.getSecret());
        return ResultBean.success(encryptedResp);
    }

    @LogPrint
    @Operation(summary = "注销Token")
    @PostMapping("/revoke")
    public ResultBean<Boolean> logout(@RequestHeader("token") String token) {
        StpOpenApiUtils.logout(token);
        return ResultBean.success();
    }

}
