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

const COMMUNICATIONS_PATH = '/communications';

function createParentMessagesPath(category?: ParentMessageCategory): string {
  if (!category) {
    return `${COMMUNICATIONS_PATH}/parent-messages`;
  }

  return `${COMMUNICATIONS_PATH}/parent-messages?${new URLSearchParams({ category }).toString()}`;
}

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

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

export function listParentMessages(category?: ParentMessageCategory): Promise<ApiListResponse<ParentMessageDto>> {
  return apiRequest<ApiListResponse<ParentMessageDto>>(createParentMessagesPath(category));
}

export function createParentMessage(request: ParentMessageCreateDto): Promise<ParentMessageDto> {
  return apiRequest<ParentMessageDto>(`${COMMUNICATIONS_PATH}/parent-messages`, {
    method: 'POST',
    body: { data: request },
  });
}

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 },
  });
}
