package cn.nianxx.thhotel.platform.audit.repository;

import cn.nianxx.thhotel.platform.audit.domain.PlatformAdminAuditLogEntity;
import cn.nianxx.thhotel.platform.audit.mapper.PlatformAdminAuditLogMapper;
import cn.nianxx.thhotel.platform.common.dto.PlatformPageSnapshot;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Repository;

/**
 * 基于 MyBatis-Plus 的平台管理审计仓储实现。
 */
@Repository
public class MybatisPlatformAdminAuditLogRepository implements PlatformAdminAuditLogRepository {

    private final PlatformAdminAuditLogMapper auditLogMapper;

    public MybatisPlatformAdminAuditLogRepository(PlatformAdminAuditLogMapper auditLogMapper) {
        this.auditLogMapper = auditLogMapper;
    }

    /**
     * 新增管理审计记录。
     */
    @Override
    public void insert(PlatformAdminAuditLogEntity entity) {
        auditLogMapper.insert(entity);
    }

    /**
     * 分页查询管理审计记录。
     */
    @Override
    public PlatformPageSnapshot<PlatformAdminAuditLogEntity> query(
            String targetType,
            String targetId,
            String action,
            int pageNum,
            int pageSize) {
        Page<PlatformAdminAuditLogEntity> page = auditLogMapper.selectPage(Page.of(pageNum, pageSize),
                Wrappers.<PlatformAdminAuditLogEntity>lambdaQuery()
                        .eq(targetType != null && !targetType.isBlank(), PlatformAdminAuditLogEntity::getTargetType, targetType)
                        .eq(targetId != null && !targetId.isBlank(), PlatformAdminAuditLogEntity::getTargetId, targetId)
                        .eq(action != null && !action.isBlank(), PlatformAdminAuditLogEntity::getAction, action)
                        .orderByDesc(PlatformAdminAuditLogEntity::getOccurredAt)
                        .orderByDesc(PlatformAdminAuditLogEntity::getId));
        return new PlatformPageSnapshot<>(page.getRecords(), page.getTotal(), pageNum, pageSize);
    }
}
