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

import com.red.circle.other.domain.gateway.RoomRedPacketGateway;
import com.red.circle.other.domain.redpacket.RoomRedPacket;
import com.red.circle.other.domain.redpacket.RoomRedPacketStatus;
import com.red.circle.other.infra.convertor.RoomRedPacketConvertor;
import com.red.circle.other.infra.database.rds.dao.redpacket.RoomRedPacketDAO;
import com.red.circle.other.infra.database.rds.entity.RoomRedPacketEntity;
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;

/**
 * 房间红包网关实现
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RoomRedPacketGatewayImpl implements RoomRedPacketGateway {

    private final RoomRedPacketDAO roomRedPacketDAO;

    @Override
    public void save(RoomRedPacket redPacket) {
        RoomRedPacketEntity entity = RoomRedPacketConvertor.toEntity(redPacket);
        roomRedPacketDAO.insert(entity);
        redPacket.setId(entity.getId());
    }

    @Override
    public RoomRedPacket findByPacketId(String packetId) {
        RoomRedPacketEntity entity = roomRedPacketDAO.selectByPacketId(packetId);
        return RoomRedPacketConvertor.toDomain(entity);
    }

    @Override
    public boolean decrementPacket(String packetId, Long amount) {
        int rows = roomRedPacketDAO.decrementPacket(packetId, amount);
        return rows > 0;
    }

    @Override
    public void updateStatus(String packetId, RoomRedPacketStatus status) {
        roomRedPacketDAO.updateStatus(packetId, status.getCode());
    }

    @Override
    public void updateRefundStatus(String packetId, Integer refundStatus) {
        roomRedPacketDAO.updateRefundStatus(packetId, refundStatus);
    }

    @Override
    public List<RoomRedPacket> findExpiredAndNotRefunded(LocalDateTime now) {
        List<RoomRedPacketEntity> entities = roomRedPacketDAO.selectExpiredAndNotRefunded(now);
        return entities.stream()
                .map(RoomRedPacketConvertor::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<RoomRedPacket> findByRoomId(Long roomId, Integer current, Integer size) {
        int offset = (current - 1) * size;
        List<RoomRedPacketEntity> entities = roomRedPacketDAO.selectByRoomId(roomId, offset, size);
        return entities.stream()
                .map(RoomRedPacketConvertor::toDomain)
                .collect(Collectors.toList());
    }
}
