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

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.app.convertor.UserRedPacketAppConvertor;
import com.red.circle.other.app.dto.clientobject.SimpleUserInfoCO;
import com.red.circle.other.app.dto.clientobject.UserRedPacketCO;
import com.red.circle.other.app.dto.cmd.QueryUserRedPacketDetailCmd;
import com.red.circle.other.domain.gateway.UserRedPacketGateway;
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.UserRedPacket;
import com.red.circle.other.inner.asserts.OtherErrorCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 查询用户红包详情执行器
 */
@Component
@RequiredArgsConstructor
public class QueryUserRedPacketDetailQryExe {

    private final UserRedPacketGateway userRedPacketGateway;
    private final UserProfileGateway userProfileGateway;

    public UserRedPacketCO execute(QueryUserRedPacketDetailCmd cmd) {
        UserRedPacket redPacket = userRedPacketGateway.findByPacketId(cmd.getPacketId());
        ResponseAssert.notNull(OtherErrorCode.RED_PACKET_NOT_FOUND, redPacket);

        UserProfile senderProfile = userProfileGateway.getByUserId(redPacket.getSenderUserId());
        UserProfile receiverProfile = userProfileGateway.getByUserId(redPacket.getReceiverUserId());

        SimpleUserInfoCO senderInfo = buildSimpleUserInfo(senderProfile);
        SimpleUserInfoCO receiverInfo = buildSimpleUserInfo(receiverProfile);

        return UserRedPacketAppConvertor.toDetailCO(redPacket, senderInfo, receiverInfo);
    }

    private SimpleUserInfoCO buildSimpleUserInfo(UserProfile userProfile) {
        if (userProfile == null) {
            return null;
        }
        return SimpleUserInfoCO.builder()
                .userId(userProfile.getId())
                .account(userProfile.getAccount())
                .nickName(userProfile.getUserNickname())
                .avatar(userProfile.getUserAvatar())
                .build();
    }
}
