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

import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.app.convertor.PropCouponConvertor;
import com.red.circle.other.app.dto.clientobject.PropCouponCO;
import com.red.circle.other.app.dto.cmd.PropCouponQueryCmd;
import com.red.circle.other.domain.gateway.PropCouponGateway;
import com.red.circle.other.domain.propcoupon.PropCoupon;
import com.red.circle.other.domain.propcoupon.PropCouponStatus;
import com.red.circle.other.domain.propcoupon.PropCouponType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 查询道具券列表执行器
 *
 * @author system
 * @date 2025-11-05
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PropCouponListQryExe {

    private final PropCouponGateway propCouponGateway;

    /**
     * 执行查询道具券列表
     */
    public PageResult<PropCouponCO> execute(PropCouponQueryCmd cmd) {
        // 1. 获取当前用户ID
        Long userId = cmd.requiredReqUserId();

        // 2. 解析查询条件
        PropCouponType couponType = null;
        if (cmd.getCouponType() != null) {
            couponType = PropCouponType.getByCode(cmd.getCouponType());
        }

        PropCouponStatus status = PropCouponStatus.UNUSED;

        // 3. 查询券列表（分页）
        List<PropCoupon> propCoupons = propCouponGateway.selectByUserId(
                userId,
                couponType,
                status,
                cmd.getCurrent().intValue(),
                cmd.getSize().intValue()
        );
        // 4. 统计总数
        Long total = propCouponGateway.countByUserId(userId, couponType, status);

        // 5. 转换为CO对象
        List<PropCouponCO> couponCOList = propCoupons.stream()
                .map(PropCouponConvertor::toClientObject)
                .collect(Collectors.toList());

        // 6. 返回分页结果
        PageResult<PropCouponCO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setRecords(couponCOList);
        pageResult.setCurrent(cmd.getCurrent());
        pageResult.setSize(cmd.getSize());
        return pageResult;
    }
}
