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.productsupplier.ProductSupplierRequest;
import org.example.petshopdesktop.api.dto.productsupplier.ProductSupplierResponse;

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

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

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

    public static ProductSupplierApi getInstance() {
        return INSTANCE;
    }

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

    public ProductSupplierResponse createProductSupplier(ProductSupplierRequest request) throws Exception {
        return apiClient.post("/api/v1/product-suppliers", request, ProductSupplierResponse.class);
    }

    public ProductSupplierResponse updateProductSupplier(Long productId, Long supplierId, ProductSupplierRequest request) throws Exception {
        return apiClient.put("/api/v1/product-suppliers/" + productId + "/" + supplierId, request, ProductSupplierResponse.class);
    }

    public void deleteProductSupplier(Long productId, Long supplierId) throws Exception {
        apiClient.delete("/api/v1/product-suppliers/" + productId + "/" + supplierId);
    }
}
