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.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.other.repository.BankRepository;
import com.ecep.contract.model.Bank;

@Lazy
@Service
@CacheConfig(cacheNames = "bank")
public class BankService implements IEntityService<Bank> {
    @Lazy
    @Autowired
    private BankRepository bankRepository;

    public Bank findById(Integer id) {
        return bankRepository.findById(id).orElse(null);
    }

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

    @Override
    public Specification<Bank> 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 + "%"));
        };
    }

    public List<Bank> search(String searchText) {
        Specification<Bank> spec = getSpecification(searchText);
        return bankRepository.findAll(spec, Pageable.ofSize(10)).getContent();
    }

    public Bank findByName(String name) {
        return bankRepository.findFirstByName(name).orElse(null);
    }

    public Bank save(Bank entity) {
        return bankRepository.save(entity);
    }

    public void delete(Bank entity) {
        bankRepository.delete(entity);
    }
}
