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.InventoryHistoryPriceRepository;
import com.ecep.contract.model.Inventory;
import com.ecep.contract.model.InventoryHistoryPrice;

import jakarta.persistence.criteria.Path;

@Lazy
@Service
@CacheConfig(cacheNames = "inventory-history-price")
public class InventoryHistoryPriceService implements IEntityService<InventoryHistoryPrice> {
    @Lazy
    @Autowired
    InventoryHistoryPriceRepository repository;

    @Override
    public InventoryHistoryPrice findById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public Specification<InventoryHistoryPrice> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            Path<Inventory> inventory = root.get("inventory");
            return builder.or(
                    builder.like(inventory.get("name"), "%" + searchText + "%"),
                    builder.like(inventory.get("specification"), "%" + searchText + "%")
            );
        };
    }

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


    public List<InventoryHistoryPrice> findAllByInventory(Inventory inventory) {
        return repository.findAllByInventory(inventory);
    }

    @Override
    public void delete(InventoryHistoryPrice entity) {
        repository.delete(entity);
    }

    @Override
    public InventoryHistoryPrice save(InventoryHistoryPrice entity) {
        return repository.save(entity);
    }

}
