package com.ecep.contract.ds.other.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 com.ecep.contract.ds.other.repository.InventoryCatalogRepository;
import com.ecep.contract.model.InventoryCatalog;

@Lazy
@Service
@CacheConfig(cacheNames = "inventory-catalog")
public class InventoryCatalogService {
    @Lazy
    @Autowired
    private InventoryCatalogRepository repository;

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


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

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

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

    @Caching(
            evict = {
                    @CacheEvict(key = "#p0.id"),
                    @CacheEvict(key = "'code-'+#p0.code"),
                    @CacheEvict(key = "'name-'+#p0.code")
            }
    )
    public InventoryCatalog save(InventoryCatalog entity) {
        return repository.save(entity);
    }

    public List<InventoryCatalog> search(String searchText) {
        Specification<InventoryCatalog> spec = (root, query, builder) -> {
            return builder.or(builder.like(root.get("code"), "%" + searchText + "%"),
                    builder.like(root.get("name"), "%" + searchText + "%"));
        };
        return repository.findAll(spec, Pageable.ofSize(10)).getContent();
    }
}
