package com.izouma.nineth.service;

import com.izouma.nineth.annotations.RedisLock;
import com.izouma.nineth.domain.PriceList;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.repo.CollectionRepo;
import com.izouma.nineth.repo.PriceListRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@AllArgsConstructor
public class PriceListService {

    private PriceListRepo  priceListRepo;
    private CollectionRepo collectionRepo;
    private CacheService   cacheService;

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

    @Scheduled(initialDelay = 1, fixedRate = 5, timeUnit = TimeUnit.MINUTES)
    @RedisLock(value = "priceList", expire = 1, unit = TimeUnit.MINUTES)
    public void schedule() {
        cacheService.clearPriceList();
        for (PriceList priceList : priceListRepo.findAll()) {
            priceList.setPrice(collectionRepo.lowestPrice(priceList.getSearch()));
            List<Long> ids = priceListRepo.lowest20(priceList.getSearch());
            if (ids != null && !ids.isEmpty()) {
                priceList.setLockNum(String.valueOf(priceListRepo.lockNum(ids)));
            } else {
                priceList.setLockNum("0");
            }
            priceListRepo.save(priceList);
        }
    }
}
