package com.reading.platform.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.reading.platform.common.security.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus Configuration
 */
@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                // 时间字段自动填充
                this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, LocalDateTime.now());
                this.strictInsertFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
                // 审计用户字段自动填充（从 Security 上下文获取当前用户名）
                try {
                    String username = SecurityUtils.getCurrentUsername();
                    this.strictInsertFill(metaObject, "createdBy", String.class, username);
                    this.strictInsertFill(metaObject, "updatedBy", String.class, username);
                } catch (Exception e) {
                    // 如果无法获取当前用户（如异步线程、测试等），则不填充
                }
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                // 时间字段自动填充
                this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
                // 审计用户字段自动填充（从 Security 上下文获取当前用户名）
                try {
                    String username = SecurityUtils.getCurrentUsername();
                    this.strictUpdateFill(metaObject, "updatedBy", String.class, username);
                } catch (Exception e) {
                    // 如果无法获取当前用户（如异步线程、测试等），则不填充
                }
            }
        };
    }

}
