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.inventory.InventoryRequest;
import org.example.petshopdesktop.api.dto.inventory.InventoryResponse;

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

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

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

    public static InventoryApi getInstance() {
        return INSTANCE;
    }

    public List<InventoryResponse> listInventory(String query, Long storeId) throws Exception {
        String path = "/api/v1/inventory?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<InventoryResponse> pageResponse = apiClient.getObjectMapper().readValue(
            response,
            new TypeReference<PageResponse<InventoryResponse>>() {}
        );
        if (pageResponse == null) {
            throw new IllegalStateException("Null response from inventory endpoint");
        }
        return pageResponse.getContent();
    }

    public InventoryResponse createInventory(InventoryRequest request) throws Exception {
        return apiClient.post("/api/v1/inventory", request, InventoryResponse.class);
    }

    public InventoryResponse updateInventory(Long id, InventoryRequest request) throws Exception {
        return apiClient.put("/api/v1/inventory/" + id, request, InventoryResponse.class);
    }

    public void deleteInventory(Long id) throws Exception {
        apiClient.delete("/api/v1/inventory/" + id);
    }
}
