package com.storlead.api.config;

import com.storlead.framework.common.constant.DefContants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Set;

/**
 * storlead-api 启动模块专属接口文档分组（平台网关/登录/系统配置等）。
 */
@Configuration
public class StorleadApiSwaggerConfig {

    private static final Set<String> PLATFORM_CONTROLLER_NAMES = Set.of(
            "LoginApiController",
            "UserApiController",
            "UserController",
            "FileResourceController",
            "OrganizDataSyncApiController",
            "SystemSettingApiController",
            "SystemPersonalizeSettingApiController",
            "SystemOssConfigApiController",
            "SystemWechatConfigApiController",
            "CorpWeChatController"
    );

    @Bean
    public Docket storleadApiDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("platform-api")
                .apiInfo(platformApiInfo())
                .select()
                .apis(input -> {
                    Class<?> controllerType = input.getHandlerMethod().getBeanType();
                    String pkg = controllerType.getPackage().getName();
                    if (pkg.startsWith("com.storlead.login")) {
                        return true;
                    }
                    if ("com.storlead.system".equals(pkg)) {
                        return true;
                    }
                    return pkg.startsWith("com.storlead.system.controller")
                            && PLATFORM_CONTROLLER_NAMES.contains(controllerType.getSimpleName());
                })
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(java.util.Collections.singletonList(
                        new ApiKey("token", DefContants.ACCESS_TOKEN, "header")));
    }

    private ApiInfo platformApiInfo() {
        return new ApiInfoBuilder()
                .title("平台网关 API（storlead-api）")
                .description("storlead-api 模块：登录认证、租户登录、验证码、OSS/微信/个性化配置等")
                .version("1.0")
                .build();
    }
}
