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.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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

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

            StringBuilder result = new StringBuilder("""
                    <!DOCTYPE html>
                    <html>
                    <body>""");
            result.append("<p>connection to jest klasa: ").append(c.getClass().getName()).append("</p>");
            result.append("""
                    <h2>Lista produktów</h2>
                    <ul>
                    """);
            try(ResultSet rs = stmt.executeQuery()) {
                while(rs.next()) {
                    result.append("<li>")
                            .append(rs.getString("product_name"))
                            .append(" za ")
                            .append(rs.getString("price"))
                            .append("</li>\n");
                }
            }
            result.append("""
                    </ul>
                    </body>
                    </html>
                    """);
            return result.toString();

        } catch (SQLException e) {
            throw new WebApplicationException("Błąd bazy danych. " + e.getMessage(), e, 500);
        }
    }
}