package com.yaoai.admin.audit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yaoai.admin.audit.dto.AuditLogQuery;
import com.yaoai.admin.auth.StpAdminUtil;
import com.yaoai.admin.common.PageResult;
import com.yaoai.domain.entity.AdminAuditLog;
import com.yaoai.domain.mapper.AdminAuditLogMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class AdminAuditQueryService {

    private final AdminAuditLogMapper adminAuditLogMapper;

    public PageResult<AdminAuditLog> list(AuditLogQuery query) {
        long page = Math.max(1, query.getPage());
        long size = Math.max(1, Math.min(query.getSize(), 100));
        long offset = (page - 1) * size;
        LambdaQueryWrapper<AdminAuditLog> wrapper = buildQuery(query);
        long total = adminAuditLogMapper.selectCount(wrapper);
        return new PageResult<>(
                adminAuditLogMapper.selectList(buildQuery(query)
                        .orderByDesc(AdminAuditLog::getCreatedAt)
                        .last("LIMIT " + size + " OFFSET " + offset)),
                total,
                page,
                size);
    }

    private LambdaQueryWrapper<AdminAuditLog> buildQuery(AuditLogQuery query) {
        LambdaQueryWrapper<AdminAuditLog> wrapper = Wrappers.<AdminAuditLog>lambdaQuery();
        boolean superAdmin = "SUPER_ADMIN".equals(StpAdminUtil.getRole());
        if (superAdmin && query.getAdminId() != null) {
            wrapper.eq(AdminAuditLog::getAdminUserId, query.getAdminId());
        } else if (!superAdmin) {
            wrapper.eq(AdminAuditLog::getAdminUserId, StpAdminUtil.getLoginIdAsLong());
        }
        if (StringUtils.hasText(query.getAction())) {
            wrapper.eq(AdminAuditLog::getAction, query.getAction());
        }
        if (StringUtils.hasText(query.getResourceType())) {
            wrapper.eq(AdminAuditLog::getResourceType, query.getResourceType());
        }
        if (query.getFrom() != null) {
            wrapper.ge(AdminAuditLog::getCreatedAt, query.getFrom());
        }
        if (query.getTo() != null) {
            wrapper.le(AdminAuditLog::getCreatedAt, query.getTo());
        }
        return wrapper;
    }
}
