package sklep.alternatywne_dostepy_do_bazy;

import jakarta.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sklep.model.Product;

import java.util.List;


@Controller
@RequestMapping("/alt2/products")
public class ProductController_v2 {
    @Autowired
    private EntityManager em;

    @GetMapping(produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String readAll() {
        List<Product> products = em.createNamedQuery("Product.findAll", Product.class).getResultList();
        StringBuilder sb = new StringBuilder("Lista produktów:\n");
        for (Product product : products) {
            sb.append(" * ")
                    .append(product.getProductName())
                    .append(" za cenę ")
                    .append(product.getPrice())
                    .append('\n');
        }
        return sb.toString();
    }
}
