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.user.UserRequest;
import org.example.petshopdesktop.api.dto.user.UserResponse;

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

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

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

    public static CustomerApi getInstance() {
        return INSTANCE;
    }

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

    public UserResponse updateCustomer(Long id, UserRequest request) throws Exception {
        return apiClient.put("/api/v1/customers/" + id, request, UserResponse.class);
    }

    public UserResponse createCustomer(UserRequest request) throws Exception {
        return apiClient.post("/api/v1/customers", request, UserResponse.class);
    }

    public UserResponse getCustomerById(Long id) throws Exception {
        return apiClient.get("/api/v1/customers/" + id, UserResponse.class);
    }
}
