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.ProjectSaleTypeRepository;
import com.ecep.contract.model.ProjectSaleType;

@Lazy
@Service
@CacheConfig(cacheNames = "sale-type")
public class SaleTypeService implements IEntityService<ProjectSaleType> {
    @Lazy
    @Autowired
    private ProjectSaleTypeRepository saleTypeRepository;

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

    public ProjectSaleType findByName(String name) {
        return saleTypeRepository.findByName(name).orElse(null);
    }

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

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

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

    @Override
    public Specification<ProjectSaleType> 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 = "'code-'+#p0.name"),
            @CacheEvict(key = "'all'"),
    })
    public ProjectSaleType save(ProjectSaleType type) {
        return saleTypeRepository.save(type);
    }

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