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

import cn.skcks.matrix.v2.casbin.adapter.CustomJDBCAdapter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource;
import org.casbin.jcasbin.persist.Adapter;
import org.casbin.spring.boot.autoconfigure.properties.CasbinDataSourceInitializationMode;
import org.casbin.spring.boot.autoconfigure.properties.CasbinExceptionProperties;
import org.casbin.spring.boot.autoconfigure.properties.CasbinProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

@Slf4j
@Configuration
@RequiredArgsConstructor
@ConditionalOnClass(ShardingSphereDataSource.class)
public class CasbinConfig {
    private final ShardingSphereDataSource dataSource;

    @Primary
    @Bean
    public Adapter autoConfigJdbcAdapter(CasbinProperties properties, CasbinExceptionProperties exceptionProperties) throws Exception {
        CasbinDataSourceInitializationMode initializeSchema = properties.getInitializeSchema();
        boolean autoCreateTable = initializeSchema == CasbinDataSourceInitializationMode.CREATE;
        String tableName = properties.getTableName();
        return new CustomJDBCAdapter(dataSource,exceptionProperties.isRemovePolicyFailed(),tableName, autoCreateTable);
   }
}
