package com.red.circle.other.infra.gateway;

import com.red.circle.other.domain.gateway.UserRedPacketGateway;
import com.red.circle.other.domain.redpacket.UserRedPacket;
import com.red.circle.other.domain.redpacket.UserRedPacketStatus;
import com.red.circle.other.infra.convertor.UserRedPacketConvertor;
import com.red.circle.other.infra.database.rds.dao.redpacket.UserRedPacketDAO;
import com.red.circle.other.infra.database.rds.entity.UserRedPacketEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

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

/**
 * 用户红包Gateway实现
 */
@Component
@RequiredArgsConstructor
public class UserRedPacketGatewayImpl implements UserRedPacketGateway {

    private final UserRedPacketDAO userRedPacketDAO;

    @Override
    public void save(UserRedPacket userRedPacket) {
        UserRedPacketEntity entity = UserRedPacketConvertor.toEntity(userRedPacket);
        userRedPacketDAO.insert(entity);
    }

    @Override
    public UserRedPacket findByPacketId(String packetId) {
        UserRedPacketEntity entity = userRedPacketDAO.selectByPacketId(packetId);
        return UserRedPacketConvertor.toDomain(entity);
    }

    @Override
    public boolean updateStatus(String packetId, UserRedPacketStatus status) {
        return userRedPacketDAO.updateStatus(packetId, status.getCode()) > 0;
    }

    @Override
    public boolean updateRefundStatus(String packetId, Integer refundStatus) {
        return userRedPacketDAO.updateRefundStatus(packetId, refundStatus) > 0;
    }

    @Override
    public boolean updateToGrabbed(String packetId, LocalDateTime grabbedAt) {
        return userRedPacketDAO.updateToGrabbed(packetId, grabbedAt) > 0;
    }

    @Override
    public List<UserRedPacket> findExpiredAndNotRefunded(LocalDateTime now) {
        List<UserRedPacketEntity> entities = userRedPacketDAO.selectExpiredAndNotRefunded(now);
        return entities.stream()
                .map(UserRedPacketConvertor::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<UserRedPacket> findBySenderUserId(Long senderUserId, Integer limit) {
        List<UserRedPacketEntity> entities = userRedPacketDAO.selectBySenderUserId(senderUserId, limit);
        return entities.stream()
                .map(UserRedPacketConvertor::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<UserRedPacket> findByReceiverUserId(Long receiverUserId, Integer limit) {
        List<UserRedPacketEntity> entities = userRedPacketDAO.selectByReceiverUserId(receiverUserId, limit);
        return entities.stream()
                .map(UserRedPacketConvertor::toDomain)
                .collect(Collectors.toList());
    }
}
