package com.lesingle.creation.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lesingle.creation.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus 自动填充处理器
 * <p>
 * 自动填充创建人、创建时间、更新人、更新时间字段
 *
 * @author lesingle
 * @since 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MyMetaObjectHandler implements MetaObjectHandler {

    private final SecurityUtils securityUtils;

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("执行插入操作，自动填充审计字段");
        LocalDateTime now = LocalDateTime.now();

        // 填充创建时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);

        // 填充创建人（从 UserContext 获取当前用户名）
        this.strictInsertFill(metaObject, "createBy", String.class, getCurrentUsername());

        // 填充更新时间
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, now);

        // 填充更新人
        this.strictInsertFill(metaObject, "updateBy", String.class, getCurrentUsername());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("执行更新操作，自动填充审计字段");
        LocalDateTime now = LocalDateTime.now();

        // 填充更新时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, now);

        // 填充更新人
        this.strictUpdateFill(metaObject, "updateBy", String.class, getCurrentUsername());
    }

    /**
     * 获取当前登录用户名
     * 从 SecurityUtils 获取，非登录场景返回 "system"
     */
    private String getCurrentUsername() {
        try {
            return securityUtils.getCurrentUsernameStr();
        } catch (Exception e) {
            log.warn("获取当前用户名失败，使用默认值：{}", e.getMessage());
            return "system";
        }
    }

}
