package com.ecep.contract.service;

import java.util.List;

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;

import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.ProductTypeViewModel;
import com.ecep.contract.vo.ProductTypeVo;

@Service
@CacheConfig(cacheNames = "product-type")
public class ProductTypeService extends QueryService<ProductTypeVo, ProductTypeViewModel> {
    @Cacheable(key = "#p0")
    @Override
    public ProductTypeVo findById(Integer id) {
        return super.findById(id);
    }

    public ProductTypeVo findByName(String name) {
        Page<ProductTypeVo> page = findAll(ParamUtils.builder().equals("name", name).build(), Pageable.unpaged());
        if (page.isEmpty()) {
            return null;
        }
        return page.getContent().getFirst();
    }

    @Cacheable(key = "'types'")
    @Override
    public List<ProductTypeVo> findAll() {
        return super.findAll();
    }

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

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

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

}
