package com.xindazhou.framework.security.config;

import com.xindazhou.framework.security.core.filter.ServiceJwtAuthenticationFilter;
import com.xindazhou.framework.security.core.jwt.ServiceJwtUtil;
import com.xindazhou.framework.security.core.rpc.ServiceJwtRequestInterceptor;
import com.xindazhou.framework.web.core.handler.GlobalExceptionHandler;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
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.context.annotation.Bean;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.filter.GenericFilterBean;

/**
 * 服务间 JWT 自动配置
 *
 * @author xindazhou
 */
@Slf4j
@AutoConfiguration
@ConditionalOnProperty(prefix = "xdz.security.service-jwt", name = "enabled", havingValue = "true", matchIfMissing = false)
@EnableConfigurationProperties(SecurityProperties.class)
public class ServiceJwtAutoConfiguration {

    @Value("${spring.application.name:unknown}")
    private String serviceName;

    @Value("${xdz.security.service-jwt.private-key-path:}")
    private String privateKeyPath;

    @Value("${xdz.security.service-jwt.public-key-path:}")
    private String publicKeyPath;

    @Value("${xdz.security.service-jwt.expire-time:3600}")
    private Long expireTime;

    private final ResourceLoader resourceLoader;

    public ServiceJwtAutoConfiguration(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @PostConstruct
    public void init() {
        ServiceJwtUtil.init(privateKeyPath, publicKeyPath, serviceName, expireTime, resourceLoader);
        log.info("服务间 JWT 初始化完成: serviceName={}", serviceName);
    }

    @Bean
    public ServiceJwtRequestInterceptor serviceJwtRequestInterceptor() {
        return new ServiceJwtRequestInterceptor();
    }

    @Bean
    public GenericFilterBean serviceJwtAuthenticationFilter(GlobalExceptionHandler globalExceptionHandler) {
        return new ServiceJwtAuthenticationFilter(globalExceptionHandler);
    }

}

