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.nio.file.Path;
import java.util.List;

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

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

    public static UserApi getInstance() {
        return INSTANCE;
    }

    public List<UserResponse> listUsers(String query) throws Exception {
        String path = "/api/v1/users?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 users endpoint");
        }
        return pageResponse.getContent();
    }

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

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

    public void uploadUserAvatar(Long userId, Path filePath) throws Exception {
        apiClient.postMultipart("/api/v1/users/" + userId + "/avatar", "avatar", filePath, Object.class);
    }

    public void deleteUserAvatar(Long userId) throws Exception {
        apiClient.delete("/api/v1/users/" + userId + "/avatar");
    }
}
