/*
 * 文 件 名:  WeatherController
 * 版    权:  华设设计集团股份有限公司
 * 描    述:  <描述>
 * 修 改 人:  lvwenbin
 * 修改时间:  2025/5/8
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.huashe.common.data.controller;

import com.huashe.common.data.mapper.AdmApiAuthMapper;
import com.huashe.common.data.model.AdmApiAuth;
import com.huashe.common.data.model.CallResponse;
import com.huashe.common.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * Api鉴权Api
 * <功能详细描述>
 *
 * @author lvwenbin
 * @version [版本号, 2025/5/8]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@RestController
@CrossOrigin(allowedHeaders = "*", allowCredentials = "false")
@RequestMapping("/auth")
@Api(value = "ApiAuthController", description = "鉴权接口")
public class ApiAuthController {
    @Autowired
    private AdmApiAuthMapper apiAuthMapper;

    /**
     * 生成鉴权记录
     */
    @RequestMapping(value = "/generateCfg", method = RequestMethod.POST)
    @ApiOperation(value = "/generateCfg", notes = "生成鉴权配置")
    @ApiResponses({ @ApiResponse(code = 200, message = "success"),
        @ApiResponse(code = 400, message = "{code:****,message:'fail'}")
    })
    public CallResponse<Void> generateCfg(@RequestBody AdmApiAuth admApiAuth) {
        CallResponse<Void> callResponse = new CallResponse<>();

        try {
            admApiAuth.setApiKey(generateApiKey());
            apiAuthMapper.insert(admApiAuth);
            callResponse.setCode(0);
            callResponse.setMessage("success");
        }
        catch (Exception e) {
            throw new BusinessException(-1, e.getMessage());
        }

        return callResponse;
    }

    public static String generateApiKey() {
        return UUID.randomUUID().toString().replace("-", "") + RandomStringUtils.randomAlphanumeric(16);
    }
}