package com.jeesharp.business.modules.contentsecurity.application.support;

import com.jeesharp.business.modules.contentsecurity.api.spi.ContentSecurityProvider;
import com.jeesharp.business.modules.contentsecurity.config.ContentSecurityProperties;
import com.jeesharp.business.modules.contentsecurity.enums.ContentTypeEnum;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 按配置从已注册 Provider 中选择实现。
 *
 * @author jeesharp
 * @since 2026-06-27
 */
@Component
@AllArgsConstructor
public class ContentSecurityProviderRouter {

    private final ContentSecurityProperties properties;
    private final List<ContentSecurityProvider> providers;

    public ContentSecurityProvider resolve(ContentTypeEnum contentType) {
        List<String> chain = contentType == ContentTypeEnum.IMAGE
                ? properties.getImageProviders()
                : properties.getTextProviders();
        Map<String, ContentSecurityProvider> byCode = providers.stream()
                .collect(Collectors.toMap(ContentSecurityProvider::providerCode, Function.identity(), (a, b) -> a));
        for (String code : chain) {
            ContentSecurityProvider p = byCode.get(code);
            if (p != null && p.supports(contentType)) {
                return p;
            }
        }
        ContentSecurityProvider fallback = byCode.get(properties.getDefaultProvider());
        if (fallback != null && fallback.supports(contentType)) {
            return fallback;
        }
        throw new IllegalStateException("未找到可用的内容安全 Provider，contentType=" + contentType);
    }
}
