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

import java.util.List;

import com.ecep.contract.EntityService;
import com.ecep.contract.QueryService;
import com.ecep.contract.model.SalesOrder;
import com.ecep.contract.util.SpecificationUtils;
import com.fasterxml.jackson.databind.JsonNode;
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 extends EntityService<SalesOrderItem, Integer> implements IEntityService<SalesOrderItem>, QueryService<SalesOrderItem> {
    @Lazy
    @Autowired
    private SalesOrderItemRepository repository;

    @Override
    public SalesOrderItemRepository getRepository() {
        return repository;
    }

    @Override
    public SalesOrderItem createNewEntity() {
        return new SalesOrderItem();
    }

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


    @Override
    protected Specification<SalesOrderItem> buildSearchSpecification(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
    protected Specification<SalesOrderItem> buildParameterSpecification(JsonNode paramsNode) {
        Specification<SalesOrderItem> spec = null;
        spec = SpecificationUtils.andFieldEqualParam(spec, paramsNode, "code");
        spec = SpecificationUtils.andParam(spec, paramsNode, "order");
        return spec;
    }

    @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);
    }
}
