package com.lideeyunji.tool.framework.apilog.config;

import com.lideeyunji.tool.framework.apilog.core.filter.ApiAccessLogFilter;
import com.lideeyunji.tool.framework.apilog.core.service.ApiAccessLogFrameworkService;
import com.lideeyunji.tool.framework.apilog.core.service.ApiAccessLogFrameworkServiceImpl;
import com.lideeyunji.tool.framework.apilog.core.service.ApiErrorLogFrameworkService;
import com.lideeyunji.tool.framework.apilog.core.service.ApiErrorLogFrameworkServiceImpl;
import com.lideeyunji.tool.framework.common.enums.WebFilterOrderEnum;
import com.lideeyunji.tool.framework.web.config.WebProperties;
import com.lideeyunji.tool.framework.web.config.WebAutoConfiguration;
import com.lideeyunji.service.infra.api.IApiAccessLogApi;
import com.lideeyunji.service.infra.api.IApiErrorLogApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import javax.servlet.Filter;

@AutoConfiguration(after = WebAutoConfiguration.class)
@EnableConfigurationProperties(ApiLogProperties.class)
public class ApiLogAutoConfiguration {

    @Bean
    public ApiAccessLogFrameworkService apiAccessLogFrameworkService(IApiAccessLogApi apiAccessLogApi) {
        return new ApiAccessLogFrameworkServiceImpl(apiAccessLogApi);
    }

    @Bean
    public ApiErrorLogFrameworkService apiErrorLogFrameworkService(IApiErrorLogApi apiErrorLogApi) {
        return new ApiErrorLogFrameworkServiceImpl(apiErrorLogApi);
    }

    /**
     * 创建 ApiAccessLogFilter Bean，记录 API 请求日志
     */
    @Bean
    @ConditionalOnProperty(prefix = "lideeyunji.access-log", value = "enable", matchIfMissing = true) // 允许使用 lideeyunji.access-log.enable=false 禁用访问日志
    public FilterRegistrationBean<ApiAccessLogFilter> apiAccessLogFilter(WebProperties webProperties,
                                                                         @Value("${spring.application.name}") String applicationName,
                                                                         ApiAccessLogFrameworkService apiAccessLogFrameworkService) {
        ApiAccessLogFilter filter = new ApiAccessLogFilter(webProperties, applicationName, apiAccessLogFrameworkService);
        return createFilterBean(filter, WebFilterOrderEnum.API_ACCESS_LOG_FILTER);
    }

    private static <T extends Filter> FilterRegistrationBean<T> createFilterBean(T filter, Integer order) {
        FilterRegistrationBean<T> bean = new FilterRegistrationBean<>(filter);
        bean.setOrder(order);
        return bean;
    }

}
