package com.ecep.contract.service;

import com.ecep.contract.converter.InventoryCatalogStringConverter;
import javafx.util.StringConverter;
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.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.InventoryCatalogViewModel;
import com.ecep.contract.vo.InventoryCatalogVo;

@Service
@CacheConfig(cacheNames = "inventory-catalog")
public class InventoryCatalogService extends QueryService<InventoryCatalogVo, InventoryCatalogViewModel> {
    private StringConverter<InventoryCatalogVo> stringConverter = new InventoryCatalogStringConverter<>(this);

    @Cacheable(key = "#p0")
    @Override
    public InventoryCatalogVo findById(Integer id) {
        return super.findById(id);
    }

    public InventoryCatalogVo findByName(String name) {
        Page<InventoryCatalogVo> page = findAll(ParamUtils.builder().equals("name", name).build(), Pageable.ofSize(1));
        if (page.isEmpty()) {
            return null;
        }
        return page.getContent().getFirst();
    }

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

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

    @Override
    public StringConverter<InventoryCatalogVo> getStringConverter() {
        return stringConverter;
    }
}
