package cn.skcks.matrix.v2.services.casbin;

import cn.skcks.matrix.v2.model.route.dto.RouteInfo;
import cn.skcks.matrix.v2.services.role.RoleService;
import cn.skcks.matrix.v2.services.route.RouteService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.casbin.jcasbin.main.Enforcer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Order(10)
@Service
@RequiredArgsConstructor
public class CasbinInitService implements CommandLineRunner {
    private final WebApplicationContext applicationContext;
    private final List<CasbinRegister> registers = new ArrayList<>();
    private final RoleService roleService;
    private final Enforcer enforcer;
    private final RouteService routeService;

    @Override
    public void run(String... args) {
        // 从 Spring 容器中获取 CasbinRegister
        applicationContext.getBeansOfType(CasbinRegister.class).forEach((name, clz) -> {
            log.info("[casbin] 添加 注册器 {}", name);
            registers.add(clz);
        });

        List<RouteInfo> routes = routeService.getRoutes();

        // 并行 执行所有注册器
        registers.parallelStream().forEach(register -> {
            register.register(enforcer, routes, roleService);
        });
    }
}
