package com.ecep.contract.ds.contract.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.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ecep.contract.IEntityService;
import com.ecep.contract.ds.contract.repository.SalesOrderItemRepository;
import com.ecep.contract.model.SalesOrderItem;

@Lazy
@Service
@CacheConfig(cacheNames = "contract-sale-order-item")
public class SalesOrderItemService implements IEntityService<SalesOrderItem> {
    @Lazy
    @Autowired
    private SalesOrderItemRepository repository;

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

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

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

    @Caching(
            evict = {
                    @CacheEvict(key = "#p0.id"),
            }
    )
    @Override
    public void delete(SalesOrderItem entity) {
        repository.delete(entity);
    }

    @Caching(
            evict = {
                    @CacheEvict(key = "#p0.id"),
            }
    )
    @Override
    public SalesOrderItem save(SalesOrderItem entity) {
        return repository.save(entity);
    }

    public List<SalesOrderItem> findAll(Specification<SalesOrderItem> spec, Sort sort) {
        return repository.findAll(spec, sort);
    }
}
