package org.qinan.safetyeval.start.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
@ConfigurationProperties(prefix = "safety-eval.security")
public class WebSecurityProperties {

    private List<String> permitAllPaths = new ArrayList<>();
    private List<String> permitAllPrefixes = new ArrayList<>();
    private List<String> authenticatedPaths = new ArrayList<>();
    private List<String> authenticatedPrefixes = new ArrayList<>();

    public String[] permitAllPatterns() {
        return patterns(permitAllPaths, permitAllPrefixes);
    }

    public String[] authenticatedPatterns() {
        return patterns(authenticatedPaths, authenticatedPrefixes);
    }

    private String[] patterns(List<String> paths, List<String> prefixes) {
        List<String> patterns = new ArrayList<>();
        for (String path : safe(paths)) {
            String normalized = normalizePath(path);
            if (normalized != null) {
                patterns.add(normalized);
            }
        }
        for (String prefix : safe(prefixes)) {
            String normalized = normalizePath(prefix);
            if (normalized != null) {
                patterns.add(normalized.endsWith("/**") ? normalized : stripTrailingSlash(normalized) + "/**");
            }
        }
        return patterns.toArray(new String[0]);
    }

    private List<String> safe(List<String> values) {
        return values == null ? Collections.emptyList() : values;
    }

    private String normalizePath(String path) {
        if (!StringUtils.hasText(path)) {
            return null;
        }
        String trimmed = path.trim();
        return trimmed.startsWith("/") ? trimmed : "/" + trimmed;
    }

    private String stripTrailingSlash(String path) {
        return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
    }

    public List<String> getPermitAllPaths() {
        return permitAllPaths;
    }

    public void setPermitAllPaths(List<String> permitAllPaths) {
        this.permitAllPaths = permitAllPaths;
    }

    public List<String> getPermitAllPrefixes() {
        return permitAllPrefixes;
    }

    public void setPermitAllPrefixes(List<String> permitAllPrefixes) {
        this.permitAllPrefixes = permitAllPrefixes;
    }

    public List<String> getAuthenticatedPaths() {
        return authenticatedPaths;
    }

    public void setAuthenticatedPaths(List<String> authenticatedPaths) {
        this.authenticatedPaths = authenticatedPaths;
    }

    public List<String> getAuthenticatedPrefixes() {
        return authenticatedPrefixes;
    }

    public void setAuthenticatedPrefixes(List<String> authenticatedPrefixes) {
        this.authenticatedPrefixes = authenticatedPrefixes;
    }
}
