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.ProductUsageRepository;
import com.ecep.contract.model.ProductUsage;

@Lazy
@Service
@CacheConfig(cacheNames = "product-usage")
public class ProductUsageService implements IEntityService<ProductUsage> {
    @Lazy
    @Autowired
    private ProductUsageRepository productUsageRepository;

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

    @Override
    public Page<ProductUsage> findAll(Specification<ProductUsage> spec, Pageable pageable) {
        return productUsageRepository.findAll(spec, pageable);
    }

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

    public ProductUsage findByName(String name) {
        return productUsageRepository.findByName(name).orElse(null);
    }

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

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

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

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