package cn.reghao.tnb.content.app.chat.service;

import cn.reghao.jutil.jdk.web.result.Result;
import cn.reghao.jutil.jdk.string.SnowFlake;
import cn.reghao.tnb.content.app.chat.db.mapper.HongbaoMapper;
import cn.reghao.tnb.content.app.chat.db.mapper.HongbaoReceiverMapper;
import cn.reghao.tnb.content.app.chat.model.dto.HongbaoDto;
import cn.reghao.tnb.content.app.chat.model.po.Hongbao;
import cn.reghao.tnb.content.app.chat.model.po.HongbaoReceiver;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author reghao
 * @date 2024-12-03 14:30:38
 */
@Service
public class HongbaoService {
    private final SnowFlake idGenerator;
    private final HongbaoMapper hongbaoMapper;
    private final HongbaoReceiverMapper hongbaoReceiverMapper;

    public HongbaoService(HongbaoMapper hongbaoMapper, HongbaoReceiverMapper hongbaoReceiverMapper) {
        this.idGenerator = new SnowFlake(1L, 1L);
        this.hongbaoMapper = hongbaoMapper;
        this.hongbaoReceiverMapper = hongbaoReceiverMapper;
    }

    public Result addHongbao(HongbaoDto hongbaoDto) {
        long hongbaoId = idGenerator.nextId();
        Hongbao hongbao = new Hongbao(hongbaoId, hongbaoDto);
        hongbaoMapper.save(hongbao);
        return Result.success();
    }

    public Result getHongbao(long hongbaoId) {
        Hongbao hongbao = hongbaoMapper.findHongbaoById(hongbaoId);
        if (hongbao == null) {
            return Result.fail("not exist");
        }

        double total = hongbaoReceiverMapper.findByHongbaoId(hongbaoId).stream()
                .map(HongbaoReceiver::getAmount)
                .mapToDouble(amount -> amount).sum();
        double remainAmount = hongbao.getAmount() - total;
        double currentAmount = getAmount(remainAmount);
        HongbaoReceiver hongbaoReceiver = new HongbaoReceiver(hongbaoId, currentAmount);
        saveHongbao(hongbaoReceiver, hongbaoId);
        return Result.success();
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveHongbao(HongbaoReceiver hongbaoReceiver, long hongbaoId) {
        hongbaoReceiverMapper.save(hongbaoReceiver);
        hongbaoMapper.updateHongbaoRemainDecr(hongbaoId);
    }

    private double getAmount(double total) {
        return total;
    }
}
