package com.ecep.contract.ds.project.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
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.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ecep.contract.IEntityService;
import com.ecep.contract.ds.project.repository.ProductTypeRepository;
import com.ecep.contract.model.ProductType;

@Lazy
@Service
@CacheConfig(cacheNames = "product-type")
public class ProductTypeService implements IEntityService<ProductType> {
    @Lazy
    @Autowired
    private ProductTypeRepository productTypeRepository;

    @Cacheable(key = "#p0")
    public ProductType findById(Integer id) {
        return productTypeRepository.findById(id).orElse(null);
    }

    @Cacheable(key = "'name-'+#p0")
    public ProductType findByName(String name) {
        return productTypeRepository.findByName(name).orElse(null);
    }

    @Cacheable(key = "'code-'+#p0")
    public ProductType findByCode(String code) {
        return productTypeRepository.findByCode(code).orElse(null);
    }

    @Cacheable(key = "'all'")
    public List<ProductType> findAll() {
        return productTypeRepository.findAll();
    }

    public Page<ProductType> findAll(Specification<ProductType> spec, Pageable pageable) {
        return productTypeRepository.findAll(spec, pageable);
    }

    @Override
    public Specification<ProductType> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("code"), "%" + searchText + "%"),
                    builder.like(root.get("name"), "%" + searchText + "%"));
        };
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'all'"),
            @CacheEvict(key = "'code-'+#p0.code"),
            @CacheEvict(key = "'name-'+#p0.name"),
    })
    public ProductType save(ProductType type) {
        return productTypeRepository.save(type);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'all'"),
            @CacheEvict(key = "'code-'+#p0.code"),
            @CacheEvict(key = "'name-'+#p0.name"),
    })
    public void delete(ProductType type) {
        productTypeRepository.delete(type);
    }
}
