package com.lanyuanxiaoyao.service.gateway;

import com.lanyuanxiaoyao.service.configuration.SecurityConfig;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import java.util.function.Function;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.Buildable;
import org.springframework.cloud.gateway.route.builder.PredicateSpec;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;

/**
 * 启动类
 *
 * @author lanyuanxiaoyao
 * @date 2024-01-15
 */
@EnableDiscoveryClient
@SpringBootApplication
@ComponentScan(
        value = "com.lanyuanxiaoyao.service",
        excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {SecurityConfig.class})
)
@EnableConfigurationProperties
@EnableEncryptableProperties
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

    private Function<PredicateSpec, Buildable<Route>> createRoute(String prefix, String target) {
        return p -> p
                .path(prefix + "/**")
                .filters(filter -> filter.rewritePath("^" + prefix, ""))
                .uri(target);
    }

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("hudi", createRoute("/hudi_services/hudi_api", "lb://service-api"))
                .route("queue", createRoute("/hudi_services/queue", "lb://service-queue"))
                .route("scheduler", createRoute("/hudi_services/service_scheduler", "lb://service-scheduler"))
                .route("web", createRoute("/hudi_services/service_web", "lb://service-web"))
                .route("services", createRoute("/hudi_services/service_cloud_query", "lb://service-cloud-query"))
                .route("exporter", createRoute("/hudi_services/service-exporter", "lb://service-exporter"))
                .build();
    }
}
