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.employee.EmployeeRequest;
import org.example.petshopdesktop.api.dto.employee.EmployeeResponse;

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

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

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

    public static EmployeeApi getInstance() {
        return INSTANCE;
    }

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

    public EmployeeResponse createEmployee(EmployeeRequest request) throws Exception {
        return apiClient.post("/api/v1/employees", request, EmployeeResponse.class);
    }

    public EmployeeResponse updateEmployee(Long id, EmployeeRequest request) throws Exception {
        return apiClient.put("/api/v1/employees/" + id, request, EmployeeResponse.class);
    }
}
