package cn.iocoder.foodnexus.module.customerpermission.config;

import cn.iocoder.foodnexus.module.customerpermission.core.aop.CustomerPermissionAnnotationAdvisor;
import cn.iocoder.foodnexus.module.customerpermission.core.db.CustomerPermissionRuleHandler;
import cn.iocoder.foodnexus.module.customerpermission.core.rule.CustomerPermissionRule;
import cn.iocoder.foodnexus.module.customerpermission.core.rule.CustomerPermissionRuleFactory;
import cn.iocoder.foodnexus.module.customerpermission.core.rule.CustomerPermissionRuleFactoryImpl;
import cn.iocoder.foodnexus.framework.mybatis.core.util.MyBatisUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.List;

/**
 * 数据权限的自动配置类
 *
 * @author 芋道源码
 */
@AutoConfiguration
public class FoodnexusCustomerPermissionAutoConfiguration {

    @Bean
    public CustomerPermissionRuleFactory customerPermissionRuleFactory(List<CustomerPermissionRule> rules) {
        return new CustomerPermissionRuleFactoryImpl(rules);
    }

    @Bean
    public CustomerPermissionRuleHandler customerPermissionRuleHandler(MybatisPlusInterceptor interceptor,
                                                                       CustomerPermissionRuleFactory ruleFactory) {
        // 创建 DataPermissionInterceptor 拦截器
        CustomerPermissionRuleHandler handler = new CustomerPermissionRuleHandler(ruleFactory);
        DataPermissionInterceptor inner = new DataPermissionInterceptor(handler);
        // 添加到 interceptor 中
        // 需要加在首个，主要是为了在分页插件前面。这个是 MyBatis Plus 的规定
        MyBatisUtils.addInterceptor(interceptor, inner, 0);
        return handler;
    }

    @Bean
    public CustomerPermissionAnnotationAdvisor customerPermissionAnnotationAdvisor() {
        return new CustomerPermissionAnnotationAdvisor();
    }

}
