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.supplier.SupplierRequest;
import org.example.petshopdesktop.api.dto.supplier.SupplierResponse;

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

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

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

    public static SupplierApi getInstance() {
        return INSTANCE;
    }

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

    public SupplierResponse createSupplier(SupplierRequest request) throws Exception {
        return apiClient.post("/api/v1/suppliers", request, SupplierResponse.class);
    }

    public SupplierResponse updateSupplier(Long id, SupplierRequest request) throws Exception {
        return apiClient.put("/api/v1/suppliers/" + id, request, SupplierResponse.class);
    }

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