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.PageResponse;
import org.example.petshopdesktop.api.dto.purchaseorder.PurchaseOrderResponse;

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

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

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

    public static PurchaseOrderApi getInstance() {
        return INSTANCE;
    }

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