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.adoption.AdoptionRequest;
import org.example.petshopdesktop.api.dto.adoption.AdoptionResponse;
import org.example.petshopdesktop.api.dto.common.BulkDeleteRequest;
import org.example.petshopdesktop.api.dto.common.PageResponse;

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

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

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

    public static AdoptionApi getInstance() {
        return INSTANCE;
    }

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

    public AdoptionResponse createAdoption(AdoptionRequest request) throws Exception {
        return apiClient.post("/api/v1/adoptions", request, AdoptionResponse.class);
    }

    public AdoptionResponse updateAdoption(Long id, AdoptionRequest request) throws Exception {
        return apiClient.put("/api/v1/adoptions/" + id, request, AdoptionResponse.class);
    }

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