import { apiRequest } from '@/shared/api/httpClient';
import { ApiListResponse } from '@/shared/types/api';
import { FrameEntryDto, FrameEntryMutationDto } from '@/shared/types/frame';

const FRAME_ENTRIES_PATH = '/frame_entries';

export interface FrameEntryFilter {
  readonly startDate?: string;
  readonly endDate?: string;
}

function toSearchParams(filter?: FrameEntryFilter): string {
  if (!filter) {
    return '';
  }

  const params = new URLSearchParams();

  if (filter.startDate) {
    params.set('startDate', filter.startDate);
  }

  if (filter.endDate) {
    params.set('endDate', filter.endDate);
  }

  const query = params.toString();
  return query ? `?${query}` : '';
}

export function listFrameEntries(filter?: FrameEntryFilter): Promise<ApiListResponse<FrameEntryDto>> {
  return apiRequest<ApiListResponse<FrameEntryDto>>(`${FRAME_ENTRIES_PATH}${toSearchParams(filter)}`);
}

export function createFrameEntry(request: FrameEntryMutationDto): Promise<FrameEntryDto> {
  return apiRequest<FrameEntryDto>(FRAME_ENTRIES_PATH, {
    method: 'POST',
    body: { data: request },
  });
}

export function updateFrameEntry(id: string, request: FrameEntryMutationDto): Promise<FrameEntryDto> {
  return apiRequest<FrameEntryDto>(`${FRAME_ENTRIES_PATH}/${id}`, {
    method: 'PUT',
    body: { data: request },
  });
}

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