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

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.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 org.springframework.util.StringUtils;

import com.ecep.contract.IEntityService;
import com.ecep.contract.QueryService;
import com.ecep.contract.ds.company.repository.InvoiceRepository;
import com.ecep.contract.model.Invoice;
import com.ecep.contract.util.SpecificationUtils;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "invoice")
public class InvoiceService implements IEntityService<Invoice>, QueryService<Invoice> {
    private static final Logger logger = LoggerFactory.getLogger(InvoiceService.class);

    @Autowired
    private InvoiceRepository repository;

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

    @Override
    public Specification<Invoice> 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("description"), "%" + searchText + "%"));

        };
    }

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

    @CacheEvict(key = "#p0.id")
    public void delete(Invoice entity) {
        repository.delete(entity);
    }

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

    public Invoice findByCode(String invoiceNumber) {
        return repository.findByCode(invoiceNumber);
    }

    @CacheEvict(key = "#p0.id")
    public Invoice save(Invoice invoice) {
        return repository.save(invoice);
    }

    @Override
    public Page<Invoice> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<Invoice> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        
        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "company");
        return findAll(spec, pageable);
    }
}
