package org.example.petshopdesktop.api.endpoints;

import com.fasterxml.jackson.core.type.TypeReference;
import org.example.petshopdesktop.api.ApiClient;
import org.example.petshopdesktop.api.dto.common.BulkDeleteRequest;
import org.example.petshopdesktop.api.dto.common.PageResponse;
import org.example.petshopdesktop.api.dto.product.ProductRequest;
import org.example.petshopdesktop.api.dto.product.ProductResponse;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;

public class ProductApi {
    private static final ProductApi INSTANCE = new ProductApi();
    private final ApiClient apiClient;

    private ProductApi() {
        this.apiClient = ApiClient.getInstance();
    }

    public static ProductApi getInstance() {
        return INSTANCE;
    }

    public List<ProductResponse> listProducts(String query, Long categoryId) throws Exception {
        String path = "/api/v1/products?page=0&size=1000";
        if (query != null && !query.isEmpty()) {
            path += "&q=" + URLEncoder.encode(query, StandardCharsets.UTF_8);
        }
        if (categoryId != null) {
            path += "&categoryId=" + categoryId;
        }
        String response = apiClient.getRawResponse(path);
        PageResponse<ProductResponse> pageResponse = apiClient.getObjectMapper().readValue(
            response,
            new TypeReference<PageResponse<ProductResponse>>() {}
        );
        if (pageResponse == null) {
            throw new IllegalStateException("Null response from products endpoint");
        }
        return pageResponse.getContent();
    }

    public List<ProductResponse> listProducts(String query) throws Exception {
        return listProducts(query, null);
    }

    public ProductResponse createProduct(ProductRequest request) throws Exception {
        return apiClient.post("/api/v1/products", request, ProductResponse.class);
    }

    public ProductResponse updateProduct(Long id, ProductRequest request) throws Exception {
        return apiClient.put("/api/v1/products/" + id, request, ProductResponse.class);
    }

    public ProductResponse uploadProductImage(Long id, Path imagePath) throws Exception {
        return apiClient.postMultipart("/api/v1/products/" + id + "/image", "image", imagePath, ProductResponse.class);
    }

    public void deleteProductImage(Long id) throws Exception {
        apiClient.delete("/api/v1/products/" + id + "/image");
    }

    public byte[] getProductImage(Long id) throws Exception {
        return apiClient.getBytes("/api/v1/products/" + id + "/image");
    }

    public void deleteProducts(List<Long> ids) throws Exception {
        apiClient.deleteWithBody("/api/v1/products", new BulkDeleteRequest(ids));
    }
}
