package cn.ey.biz.module.system.framework.third_auth;

import cn.ey.biz.framework.third.auth.oauth.cache.AuthStateCache;
import cn.ey.biz.framework.third.auth.oauth.config.AuthConfig;
import cn.ey.biz.framework.third.auth.oauth.enums.scope.AuthMicrosoftScope;
import cn.ey.biz.framework.third.auth.oauth.request.AbstractAuthMicrosoftRequest;
import cn.ey.biz.framework.third.auth.oauth.utils.AuthScopeUtils;
import cn.ey.biz.framework.third.auth.oauth.utils.UrlBuilder;

public class AuthMicrosoftCnExtRequest extends AbstractAuthMicrosoftRequest {

    public AuthMicrosoftCnExtRequest(AuthConfig config) {
        super(config, new AuthMicrosoftExtSource(config));
    }

    public AuthMicrosoftCnExtRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config, new AuthMicrosoftExtSource(config), authStateCache);
    }

    @Override
    protected String accessTokenUrl(String code) {
        return UrlBuilder.fromBaseUrl(this.source.accessToken()).queryParam("code", code).queryParam("client_id", this.config.getClientId()).queryParam("client_secret", this.config.getClientSecret()).queryParam("grant_type", "authorization_code").queryParam("scope", this.getScopes(" ", false, AuthScopeUtils.getDefaultScopes(AuthMicrosoftScope.values()))).queryParam("redirect_uri", this.config.getRedirectUri()).build();
    }

    @Override
    protected String refreshTokenUrl(String refreshToken) {
        return UrlBuilder.fromBaseUrl(this.source.refresh()).queryParam("client_id", this.config.getClientId()).queryParam("client_secret", this.config.getClientSecret()).queryParam("refresh_token", refreshToken).queryParam("grant_type", "refresh_token").queryParam("scope", this.getScopes(" ", false, AuthScopeUtils.getDefaultScopes(AuthMicrosoftScope.values()))).queryParam("redirect_uri", this.config.getRedirectUri()).build();
    }

    @Override
    public String authorize(String state) {
        return UrlBuilder.fromBaseUrl(_authorize(state)).queryParam("response_mode", "form_post").queryParam("scope", this.getScopes(" ", true, AuthScopeUtils.getDefaultScopes(AuthMicrosoftScope.values()))).build();
    }

    private String _authorize(String state) {
        return UrlBuilder.fromBaseUrl(this.source.authorize()).queryParam("response_type", "code").queryParam("client_id", this.config.getClientId()).queryParam("redirect_uri", this.config.getRedirectUri()).queryParam("state", this.getRealState(state)).build();
    }

}

