package sklep.rest;

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;

import javax.sql.DataSource;
import java.sql.*;

@Path("/b/products")
public class BProducts {
    @Inject
    private DataSource dataSource;
    // ew. adnotacja @Resource

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String allProducts() {
        try (Connection c = dataSource.getConnection();
             PreparedStatement stmt = c.prepareStatement("select product_name, price from products")) {

            StringBuilder sb = new StringBuilder("Produkty:\n");
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    sb.append(rs.getString(1)).append(" za ").append(rs.getString(2)).append('\n');
                }
            }
            return sb.toString();
        } catch (SQLException e) {
            throw new WebApplicationException("Błąd bazy danych. " + e.getMessage(), e, 500);
        }
    }
}