package com.kingdee.eas.custom.integration.weaver.service.impl;

import com.kingdee.eas.custom.integration.base.config.AppConfig;
import com.kingdee.eas.custom.integration.base.service.PlatformOAuthStrategy;
import com.kingdee.eas.custom.integration.weaver.config.WeaverConfig;
import com.kingdee.eas.custom.integration.weaver.config.WeaverConfigService;
import com.kingdee.eas.custom.integration.weaver.exception.WeaverErrorCodes;
import com.kingdee.eas.custom.integration.weaver.exception.WeaverIntegrationException;
import com.kingdee.eas.custom.integration.weaver.util.WeaverApiUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * 泛微 E10 OAuth2 策略。ecology 地址由 WeaverConfigService 读取同一份 integration-config 的 weaver 节点。
 */
@Component
public class WeaverOAuthStrategy implements PlatformOAuthStrategy {

    private static final Logger log = LoggerFactory.getLogger(WeaverOAuthStrategy.class);

    private final RestTemplate restTemplate;
    private final WeaverConfigService weaverConfigService;

    public WeaverOAuthStrategy(RestTemplate restTemplate,
                               WeaverConfigService weaverConfigService) {
        this.restTemplate = restTemplate;
        this.weaverConfigService = weaverConfigService;
    }

    @Override
    public String platform() {
        return "weaver";
    }

    @Override
    public String buildAuthUrl(AppConfig config, String state) {
        WeaverConfig weaverConfig = requireWeaverConfig();
        String authUrl = UriComponentsBuilder.fromHttpUrl(weaverConfig.getAuthorizeUrl())
                .queryParam("response_type", "code")
                .queryParam("client_id", config.getAppId())
                .queryParam("redirect_uri", config.getCallbackUrl())
                .queryParam("state", state)
                .build()
                .toUriString();
        log.info("构建泛微授权URL, appId={}, url={}", config.getAppId(), authUrl);
        return authUrl;
    }

    @Override
    public String getUserId(AppConfig config, String code) {
        WeaverConfig weaverConfig = requireWeaverConfig();
        try {
            String accessToken = WeaverApiUtils.exchangeAccessToken(
                    restTemplate, weaverConfig, config, code);
            return WeaverApiUtils.fetchProfileId(restTemplate, weaverConfig, accessToken);
        } catch (WeaverIntegrationException e) {
            throw e;
        } catch (Exception e) {
            log.error("泛微OAuth认证失败: {}", e.getMessage(), e);
            throw new WeaverIntegrationException(WeaverErrorCodes.SSO_FAILED, e.getMessage(), e);
        }
    }

    private WeaverConfig requireWeaverConfig() {
        WeaverConfig weaverConfig = weaverConfigService.getWeaverConfig();
        if (weaverConfig == null || !weaverConfig.isConfigured()) {
            throw new WeaverIntegrationException(WeaverErrorCodes.CONFIG_MISSING);
        }
        return weaverConfig;
    }
}
