package com.ecep.contract.service;

import com.ecep.contract.model.VendorGroup;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.VendorGroupViewModel;
import com.ecep.contract.vo.VendorGroupVo;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = "vendor-group")
public class VendorGroupService extends QueryService<VendorGroupVo, VendorGroupViewModel> {
    @Cacheable(key = "#id")
    @Override
    public VendorGroupVo findById(Integer id) {
        return super.findById(id);
    }

    @Override
    public VendorGroupVo createNewEntity() {
        VendorGroupVo group = new VendorGroupVo();
        group.setCode("");
        group.setName("");
        group.setDescription("");
        group.setActive(true);
        group.setPriceComparison(true);
        group.setRequireQuotationSheetForBid(true);
        group.setCanPrePurchase(false);
        return group;
    }

    public VendorGroupVo findByCode(String code) {
        Page<VendorGroupVo> page = findAll(ParamUtils.builder().equals("code", code).build(), Pageable.ofSize(1));
        if (page.isEmpty()) {
            return save(createNewEntity());
        }
        return page.getContent().getFirst();
    }

    @Caching(evict = {@CacheEvict(key = "#p0.id")})
    @Override
    public VendorGroupVo save(VendorGroupVo entity) {
        return super.save(entity);
    }

    @Caching(evict = {@CacheEvict(key = "#p0.id")})
    @Override
    public void delete(VendorGroupVo entity) {
        super.delete(entity);
    }
}
