import { apiRequest } from '@/shared/api/httpClient';
import { ApiListResponse } from '@/shared/types/api';
import type {
  CommunicationEventCancelDto,
  CommunicationEventCreateDto,
  CommunicationEventDto,
  CommunicationEventType,
  CommunicationEventUpdateDto,
} from '@/shared/types/communications';

const COMMUNICATIONS_PATH = '/communications';

function createEventsPath(type?: CommunicationEventType): string {
  if (!type) {
    return `${COMMUNICATIONS_PATH}/events`;
  }

  return `${COMMUNICATIONS_PATH}/events?${new URLSearchParams({ type }).toString()}`;
}

export function listCommunicationEvents(type?: CommunicationEventType): Promise<ApiListResponse<CommunicationEventDto>> {
  return apiRequest<ApiListResponse<CommunicationEventDto>>(createEventsPath(type));
}

export function createCommunicationEvent(request: CommunicationEventCreateDto): Promise<CommunicationEventDto> {
  return apiRequest<CommunicationEventDto>(`${COMMUNICATIONS_PATH}/events`, {
    method: 'POST',
    body: { data: request },
  });
}

export function updateCommunicationEvent(request: CommunicationEventUpdateDto): Promise<CommunicationEventDto> {
  const { id, ...data } = request;
  return apiRequest<CommunicationEventDto>(`${COMMUNICATIONS_PATH}/events/${id}`, {
    method: 'PATCH',
    body: { data },
  });
}

export function deleteCommunicationEvent(id: string): Promise<void> {
  return apiRequest<void>(`${COMMUNICATIONS_PATH}/events/${id}`, {
    method: 'DELETE',
  });
}

export function cancelCommunicationEvent(request: CommunicationEventCancelDto): Promise<CommunicationEventDto> {
  const { id, ...data } = request;
  return apiRequest<CommunicationEventDto>(`${COMMUNICATIONS_PATH}/events/${id}/cancel`, {
    method: 'POST',
    body: { data },
  });
}
