import { apiClient } from './api-client';
import type { z } from 'zod/v4';
import type {
  CabinetEventListResponseSchema,
  SpendingSummaryResponseSchema,
} from '@meshitrack/shared';

type CabinetEventListResponse = z.infer<typeof CabinetEventListResponseSchema>;
type SpendingSummaryResponse = z.infer<typeof SpendingSummaryResponseSchema>;

export async function listCabinetEvents(
  householdId: string,
  query?: {
    medicineId?: string;
    eventType?: string;
    startDate?: string;
    endDate?: string;
    cursor?: string;
    limit?: number;
  },
): Promise<CabinetEventListResponse> {
  const params = new URLSearchParams();
  if (query?.medicineId) params.set('medicineId', query.medicineId);
  if (query?.eventType) params.set('eventType', query.eventType);
  if (query?.startDate) params.set('startDate', query.startDate);
  if (query?.endDate) params.set('endDate', query.endDate);
  if (query?.cursor) params.set('cursor', query.cursor);
  if (query?.limit) params.set('limit', String(query.limit));
  const qs = params.toString();
  return apiClient.get<CabinetEventListResponse>(
    `/households/${householdId}/cabinet-events${qs ? `?${qs}` : ''}`,
  );
}

export async function getEventsByItem(
  householdId: string,
  cabinetItemId: string,
  query?: { cursor?: string; limit?: number },
): Promise<CabinetEventListResponse> {
  const params = new URLSearchParams();
  if (query?.cursor) params.set('cursor', query.cursor);
  if (query?.limit) params.set('limit', String(query.limit));
  const qs = params.toString();
  return apiClient.get<CabinetEventListResponse>(
    `/households/${householdId}/cabinet-events/by-item/${cabinetItemId}${qs ? `?${qs}` : ''}`,
  );
}

export async function getSpendingSummary(
  householdId: string,
  query?: { period?: string; medicineId?: string },
): Promise<SpendingSummaryResponse> {
  const params = new URLSearchParams();
  if (query?.period) params.set('period', query.period);
  if (query?.medicineId) params.set('medicineId', query.medicineId);
  const qs = params.toString();
  return apiClient.get<SpendingSummaryResponse>(
    `/households/${householdId}/cabinet-events/spending-summary${qs ? `?${qs}` : ''}`,
  );
}
