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.service.ServiceRequest;
import org.example.petshopdesktop.api.dto.service.ServiceResponse;

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

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

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

    public static ServiceApi getInstance() {
        return INSTANCE;
    }

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

    public ServiceResponse createService(ServiceRequest request) throws Exception {
        return apiClient.post("/api/v1/services", request, ServiceResponse.class);
    }

    public ServiceResponse updateService(Long id, ServiceRequest request) throws Exception {
        return apiClient.put("/api/v1/services/" + id, request, ServiceResponse.class);
    }

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