package com.izouma.nineth.service;

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.concurrent.TimeUnit;

@Service
@AllArgsConstructor
public class PriceListService {

    private PriceListRepo  priceListRepo;
    private CollectionRepo collectionRepo;

    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)
    public void schedule() {
        for (PriceList priceList : priceListRepo.findAll()) {
            priceList.setPrice(collectionRepo.lowestPrice(priceList.getSearch()).stripTrailingZeros().toPlainString());
            priceListRepo.save(priceList);
        }
    }
}
