package com.izouma.jiashanxia.service;

import com.izouma.jiashanxia.domain.Coupon;
import com.izouma.jiashanxia.domain.OrderInfo;
import com.izouma.jiashanxia.domain.Package;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.CouponRepo;
import com.izouma.jiashanxia.repo.OrderInfoRepo;
import com.izouma.jiashanxia.repo.PackageRepo;
import com.izouma.jiashanxia.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

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

@Service
@AllArgsConstructor
public class CouponService {

    private final CouponRepo    couponRepo;
    private final OrderInfoRepo orderInfoRepo;
    private final PackageRepo   packageRepo;

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

    /*
    可选择的优惠券
    核销套餐后，可选择的优惠券
     */
    public List<Coupon> chooseByOrder(Long orderInfoId) {
        OrderInfo orderInfo = orderInfoRepo.findById(orderInfoId).orElseThrow(new BusinessException("无订单"));
        Package aPackage = packageRepo.findById(orderInfo.getPackageId()).orElseThrow(new BusinessException("无套餐"));
        return couponRepo.findAllByIdInAndPeriodAfter(aPackage.getCouponId(), LocalDateTime.now());
    }
}
