package com.kingdee.eas.custom.integration.base.config;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * OAuth 配置，包含 redirect 白名单校验
 */
public class OAuthConfig {

    private boolean redirectEnabled;
    private List<String> redirectPrefixes = new ArrayList<>();

    public OAuthConfig() {
    }

    @SuppressWarnings("unchecked")
    public OAuthConfig(Map<String, Object> oauth) {
        Map<String, Object> redirect = (Map<String, Object>) oauth.get("redirect");
        if (redirect != null) {
            this.redirectEnabled = Boolean.TRUE.equals(redirect.get("enabledAllowed"));
            List<String> prefixes = (List<String>) redirect.get("allowedPrefixes");
            if (prefixes != null) {
                this.redirectPrefixes = new ArrayList<>(prefixes);
            }
        }
    }

    public boolean isRedirectEnabled() {
        return redirectEnabled;
    }

    public void setRedirectEnabled(boolean redirectEnabled) {
        this.redirectEnabled = redirectEnabled;
    }

    public List<String> getRedirectPrefixes() {
        return redirectPrefixes;
    }

    public void setRedirectPrefixes(List<String> redirectPrefixes) {
        this.redirectPrefixes = redirectPrefixes;
    }

    /**
     * 校验 redirect URL 是否在白名单内
     */
    public boolean isRedirectAllowed(String redirect) {
        if (!redirectEnabled) {
            return true;
        }
        if (redirect == null || redirect.trim().isEmpty()) {
            return false;
        }
        if (redirect.startsWith("/")) {
            return true;
        }
        for (String prefix : redirectPrefixes) {
            if (redirect.startsWith(prefix)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public String toString() {
        return "OAuthConfig{redirectEnabled=" + redirectEnabled +
                ", redirectPrefixes=" + redirectPrefixes + "}";
    }
}
