package com.red.circle.other.app.command.violation.query;

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.app.convertor.violation.ViolationRecordConvertor;
import com.red.circle.other.app.dto.cmd.violation.ViolationRecordPageQueryCmd;
import com.red.circle.other.app.dto.clientobject.violation.ViolationRecordCO;
import com.red.circle.other.domain.gateway.violation.ViolationRecordGateway;
import com.red.circle.other.domain.violation.ViolationRecord;
import com.red.circle.other.infra.database.rds.service.sys.AdministratorAuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 违规记录分页查询执行器
 */
@Component
@RequiredArgsConstructor
public class ViolationRecordPageQryExe {

    private final ViolationRecordGateway violationRecordGateway;
    private final AdministratorAuthService administratorAuthService;
    private final ViolationRecordConvertor violationRecordConvertor;

    public PageResult<ViolationRecordCO> execute(ViolationRecordPageQueryCmd cmd) {
        // 验证管理员权限
        ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION,
                administratorAuthService.existsAuth(cmd.requiredReqUserId(), "VIOLATION_QUERY"));

        // 分页查询
        PageResult<ViolationRecord> pageResult = violationRecordGateway.pageQuery(
                cmd.getTargetType(),
                cmd.getTargetId(),
                cmd.getViolationType(),
                cmd.getOperationType(),
                cmd.getOperatorId(),
                cmd.getCurrent().intValue(),
                cmd.getSize().intValue()
        );

        // 转换为 CO
        List<ViolationRecordCO> records = violationRecordConvertor.toCOList(pageResult.getRecords().stream().toList());

        PageResult<ViolationRecordCO> coPageResult = new PageResult<>();
        coPageResult.setRecords(records);
        coPageResult.setTotal(pageResult.getTotal());
        coPageResult.setCurrent(pageResult.getCurrent());
        coPageResult.setSize(pageResult.getSize());

        return coPageResult;
    }
}
