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

import com.red.circle.other.app.convertor.RoomRedPacketAppConvertor;
import com.red.circle.other.app.dto.clientobject.RoomRedPacketCO;
import com.red.circle.other.app.dto.cmd.QueryRoomRedPacketListCmd;
import com.red.circle.other.domain.gateway.RoomRedPacketGateway;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.domain.redpacket.RoomRedPacket;
import com.red.circle.other.infra.database.cache.service.other.RoomRedPacketCacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 查询房间红包列表执行器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class QueryRoomRedPacketListQryExe {

    private final RoomRedPacketGateway roomRedPacketGateway;
    private final RoomRedPacketCacheService roomRedPacketCacheService;
    private final UserProfileGateway userProfileGateway;

    /**
     * 执行查询
     */
    public List<RoomRedPacketCO> execute(QueryRoomRedPacketListCmd cmd) {
        Long userId = cmd.getReqUserId();
        
        // 1. 查询房间红包列表（数据库）
        List<RoomRedPacket> redPackets = roomRedPacketGateway.findByRoomId(
            cmd.getRoomId(), 
            cmd.getCurrent().intValue(),
            cmd.getSize().intValue()
        );

        Set<Long> userIds = redPackets.stream().map(RoomRedPacket::getUserId).collect(Collectors.toSet());
        Map<Long, UserProfile> profileMap = userProfileGateway.mapByUserIds(userIds);

        // 2. 转换为CO
        List<RoomRedPacketCO> result = redPackets.stream()
                .map(redPacket -> {
                    RoomRedPacketCO co = RoomRedPacketAppConvertor.toCO(redPacket);
                    
                    // 检查当前用户是否已领取
                    boolean grabbed = roomRedPacketCacheService.hasUserGrabbed(
                        redPacket.getPacketId(), userId
                    );
                    co.setGrabbed(grabbed);

                    UserProfile userProfile = profileMap.get(redPacket.getUserId());
                    if (userProfile != null) {
                        co.setAccount(userProfile.getAccount());
                        co.setUserAvatar(userProfile.getUserAvatar());
                        co.setUserName(userProfile.getUserNickname());
                        co.setUserId(userProfile.getId());
                    }

                    return co;
                })
                .collect(Collectors.toList());
        
        return result;
    }
}
