package sklep.controller;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import sklep.model.Product;
import sklep.repository.ProductRepository;

@Controller
public class Wyszukiwarka {
	@Autowired
	private ProductRepository productRepository;
	
	@GetMapping("/wyszukiwarka")
	public String wyszukiwarka(Model model,
			String name,
			BigDecimal min,
			BigDecimal max) {

		List<Product> products  = List.of();
		if(name != null && !name.isEmpty() && min == null && max == null) {
			products = productRepository.findByProductNameContainingIgnoringCase(name);
		} else if((name == null || name.isEmpty()) && (min != null || max != null)) {
			if(min == null) {
				min = BigDecimal.ZERO;
			}
			if(max == null) {
				max = BigDecimal.valueOf(1000_000_000);
			}
			
			products = productRepository.findByPriceBetween(min, max);
		} else if(name != null && !name.isEmpty() && (min != null || max != null)) {
			if(min == null) {
				min = BigDecimal.ZERO;
			}
			if(max == null) {
				max = BigDecimal.valueOf(1000_000_000);
			}
			products = productRepository.findByProductNameContainingIgnoringCaseAndPriceBetween(name, min, max);			
		}
		model.addAttribute("products", products);
		return "wyszukiwarka";
	}
}
