package sklep.rest;

import io.quarkus.panache.common.Parameters;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import sklep.model_jpa.Product;
import sklep.repo.ProductRepository;

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

@Path("/e/products")
@Produces(MediaType.APPLICATION_JSON)
public class EProducts {
    @Inject
    ProductRepository repository;

    @Inject
    PhotoUtil photoUtil;

    @GET
    public List<Product> allProducts() {
        return repository.listAll();
    }

    @Path("/{id}")
    @GET
    public Product oneProduct(@PathParam("id") Long id) {
        return repository.findByIdOptional(id)
                .orElseThrow(() -> new WebApplicationException("Nie ma takiego produktu",
                        Response.status(Response.Status.NOT_FOUND)
                                .type(MediaType.TEXT_HTML)
                                .entity("<p style='color: red'>Nie ma produktu nr "+id+"</p>")
                                .build()));
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Transactional
    public Response addProduct(Product product) {
        repository.persist(product);
        URI uri = UriBuilder.fromResource(EProducts.class).path("/{id}").build(product.getId());
        return Response.created(uri).build();
    }

    @Path("/{id}/price")
    @GET
    public BigDecimal getPrice(@PathParam("id") Long id) {
        return oneProduct(id).getPrice();
    }

    @Path("/{id}/price")
    @PUT
    @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
    @Transactional
    public void setPrice(@PathParam("id") Long id, BigDecimal price) {
        //repository.update("update Product p set p.price = ?1 where p.id = ?2", price, id);

        repository.update("update Product p set p.price = :price where p.id = :id",
                Parameters.with("price", price).and("id", id));
    }

    @DELETE
    @Path("/{id}")
    @Transactional
    public void delete(@PathParam("id") Long productId) {
        repository.deleteById(productId);
    }

    @GET
    @Path("/{id}/photo")
    @Produces("image/jpeg")
    public byte[] getPhoto(@PathParam("id") int productId) {
        return photoUtil.readBytes(productId);
    }

    @PUT
    @Path("/{id}/photo")
    @Consumes("image/jpeg")
    public void uploadPhoto(@PathParam("id") int productId, byte[] bytes) {
        photoUtil.writeBytes(productId, bytes);
    }
}