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.appointment.AppointmentRequest;
import org.example.petshopdesktop.api.dto.appointment.AppointmentResponse;
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 AppointmentApi {
    private static final AppointmentApi INSTANCE = new AppointmentApi();
    private final ApiClient apiClient;

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

    public static AppointmentApi getInstance() {
        return INSTANCE;
    }

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

    public AppointmentResponse createAppointment(AppointmentRequest request) throws Exception {
        return apiClient.post("/api/v1/appointments", request, AppointmentResponse.class);
    }

    public AppointmentResponse updateAppointment(Long id, AppointmentRequest request) throws Exception {
        return apiClient.put("/api/v1/appointments/" + id, request, AppointmentResponse.class);
    }

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