package com.nebula.erp.product.service;

import com.nebula.erp.product.model.Product;
import com.nebula.erp.product.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
public class PublicProductService {

    @Autowired
    private ProductRepository productRepository;

    public Page<Product> getProductsByTenant(int page, int size, String tenantName) {
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "id"));

        Specification<Product> spec = Specification.where(null);

        if (tenantName != null && !tenantName.isEmpty()) {
            spec = spec.and((root, query, criteriaBuilder) ->
                    criteriaBuilder.equal(root.get("tenant"), tenantName));
        }

        return productRepository.findAll(spec, pageable);
    }
}