package com.cool.modules.dingtalk.controller.admin;

import cn.hutool.json.JSONObject;
import com.cool.core.annotation.CoolRestController;
import com.cool.core.base.BaseController;
import com.cool.core.request.R;
import com.cool.modules.dingtalk.entity.DingtalkConfigEntity;
import com.cool.modules.dingtalk.service.DingtalkConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * 钉钉配置管理Controller
 */
@Slf4j
@Tag(name = "钉钉配置", description = "钉钉配置管理")
@CoolRestController(api = {"add", "update", "info"})
public class AdminDingtalkConfigController extends BaseController<DingtalkConfigService, DingtalkConfigEntity> {

    @Override
    protected void init(HttpServletRequest request, JSONObject requestParams) {
        // 钉钉配置为单例，无需分页查询
    }

    @Operation(summary = "获取钉钉配置", description = "获取当前钉钉配置（单例）")
    @GetMapping("/config")
    public R getConfig() {
        log.info("【钉钉配置Controller】获取钉钉配置");

        DingtalkConfigEntity config = this.service.getConfig();

        if (config != null) {
            log.info("【钉钉配置Controller】配置获取成功, ID: {}", config.getId());
            return R.ok(config);
        } else {
            log.warn("【钉钉配置Controller】配置不存在");
            return R.ok(null);
        }
    }

    @Operation(summary = "验证配置", description = "验证钉钉配置有效性（测试AccessToken获取）")
    @PostMapping("/validate")
    public R validateConfig(@RequestBody JSONObject data) {
        log.info("【钉钉配置Controller】验证配置, data: {}", data);

        String appKey = data.getStr("appKey");
        String appSecret = data.getStr("appSecret");

        if (appKey == null || appKey.isEmpty() || appSecret == null || appSecret.isEmpty()) {
            log.warn("【钉钉配置Controller】AppKey或AppSecret为空");
            return R.error("AppKey和AppSecret不能为空");
        }

        boolean isValid = this.service.validateConfig(appKey, appSecret);

        if (isValid) {
            log.info("【钉钉配置Controller】配置验证成功");
            return R.ok("配置验证成功，AccessToken获取正常");
        } else {
            log.error("【钉钉配置Controller】配置验证失败");
            return R.error("配置验证失败，请检查AppKey和AppSecret是否正确");
        }
    }

    @Operation(summary = "保存或更新配置", description = "保存或更新钉钉配置（单例）")
    @PostMapping("/saveOrUpdate")
    public R saveOrUpdateConfig(@RequestBody DingtalkConfigEntity entity) {
        log.info("【钉钉配置Controller】保存或更新配置, entity: {}", entity);

        try {
            DingtalkConfigEntity savedEntity = this.service.saveOrUpdateConfig(entity);
            log.info("【钉钉配置Controller】配置保存成功, ID: {}", savedEntity.getId());
            return R.ok(savedEntity);
        } catch (Exception e) {
            log.error("【钉钉配置Controller】配置保存失败", e);
            return R.error("配置保存失败: " + e.getMessage());
        }
    }
}
