package com.izouma.nineth.service;

import com.izouma.nineth.domain.AirDrop;
import com.izouma.nineth.domain.Collection;
import com.izouma.nineth.domain.Coupon;
import com.izouma.nineth.domain.UserCoupon;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.AirDropType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AirDropRepo;
import com.izouma.nineth.repo.CollectionRepo;
import com.izouma.nineth.repo.CouponRepo;
import com.izouma.nineth.repo.UserCouponRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
@AllArgsConstructor
public class AirDropService {

    private AirDropRepo    airDropRepo;
    private CouponRepo     couponRepo;
    private UserCouponRepo userCouponRepo;
    private CollectionRepo collectionRepo;

    public Page<AirDrop> all(PageQuery pageQuery) {
        return airDropRepo.findAll(JpaUtils.toSpecification(pageQuery, AirDrop.class), JpaUtils.toPageRequest(pageQuery));
    }

    @Transactional
    public AirDrop create(AirDrop record) {
        if (AirDropType.coupon == record.getType()) {
            Coupon coupon = couponRepo.findById(record.getCouponId()).orElseThrow(new BusinessException("兑换券不存在"));
            record.getUserIds().stream().parallel().forEach(userId -> {
                UserCoupon userCoupon = new UserCoupon();
                BeanUtils.copyProperties(coupon, userCoupon);
                userCoupon.setId(null);
                userCoupon.setCouponId(coupon.getId());
                userCoupon.setUserId(userId);
                userCouponRepo.save(userCoupon);
            });
        } else {
            Collection collection = collectionRepo.findById(record.getCollectionId())
                    .orElseThrow(new BusinessException("藏品不存在"));
            if (collection.getStock() < record.getUserIds().size()) {
                throw new BusinessException("藏品库存不足");
            }
        }
        return airDropRepo.save(record);
    }
}
