package com.kingdee.eas.custom.integration.feishu.controller;

import com.kingdee.eas.custom.integration.base.controller.AbstractAuthController;
import com.kingdee.eas.custom.integration.base.exception.CommonErrorCodes;
import com.kingdee.eas.custom.integration.base.exception.IntegrationException;
import com.kingdee.eas.custom.integration.base.service.IntegrationConfigService;
import com.kingdee.eas.custom.integration.base.service.OAuthService;
import com.kingdee.eas.custom.integration.base.service.StateValidator;
import com.kingdee.eas.custom.integration.base.service.detection.PlatformDetectionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 飞书认证控制器。
 *
 * <p>认证入口：{@code GET /auth/feishu?state=xxx}</p>
 * <p>回调地址：{@code GET /auth/callback/feishu/{appType}}（在飞书开放平台注册）</p>
 * <p>新增飞书应用时直接复用本类，无需改动。</p>
 */
@Controller
@RequestMapping("/auth")
public class FeishuAuthController extends AbstractAuthController {

    public FeishuAuthController(IntegrationConfigService integrationConfigService,
                                OAuthService oAuthService,
                                StateValidator stateValidator,
                                PlatformDetectionService detectionService) {
        super(integrationConfigService, oAuthService, stateValidator, detectionService);
    }

    @Override
    protected String platform() {
        return "feishu";
    }

    @GetMapping("/feishu")
    public void auth(@RequestParam(name = "state", required = false) String state,
                     HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(state)) {
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "Invalid state");
        }
        doAuth(state, response);
    }


    @GetMapping("/callback/feishu/{appType}")
    public void callback(String code, String state,
                         @PathVariable String appType,
                         HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        doCallback(code, state, request, response);
    }
}
