import { apiClient } from './api-client';
import type { z } from 'zod/v4';
import type {
  MedicinePriceRecordResponseSchema,
  MedicinePriceHistoryResponseSchema,
  StoreComparisonResponseSchema,
  MedicineSpendingAnalyticsResponseSchema,
  CreateMedicinePriceRecordSchema,
} from '@meshitrack/shared';

type MedicinePriceRecordResponse = z.infer<typeof MedicinePriceRecordResponseSchema>;
type MedicinePriceHistoryResponse = z.infer<typeof MedicinePriceHistoryResponseSchema>;
type StoreComparisonResponse = z.infer<typeof StoreComparisonResponseSchema>;
type MedicineSpendingAnalyticsResponse = z.infer<typeof MedicineSpendingAnalyticsResponseSchema>;
type CreateMedicinePriceRecordInput = z.infer<typeof CreateMedicinePriceRecordSchema>;

export async function recordPrice(
  householdId: string,
  data: CreateMedicinePriceRecordInput,
): Promise<MedicinePriceRecordResponse> {
  return apiClient.post<MedicinePriceRecordResponse>(
    `/households/${householdId}/medicine-prices`,
    data,
  );
}

export async function getPriceHistory(
  householdId: string,
  medicineId: string,
  query?: {
    storeId?: string;
    startDate?: string;
    endDate?: string;
    cursor?: string;
    limit?: number;
  },
): Promise<MedicinePriceHistoryResponse> {
  const params = new URLSearchParams();
  if (query?.storeId) params.set('storeId', query.storeId);
  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<MedicinePriceHistoryResponse>(
    `/households/${householdId}/medicine-prices/history/${medicineId}${qs ? `?${qs}` : ''}`,
  );
}

export async function compareStores(
  householdId: string,
  medicineId: string,
): Promise<StoreComparisonResponse> {
  return apiClient.get<StoreComparisonResponse>(
    `/households/${householdId}/medicine-prices/compare/${medicineId}`,
  );
}

export async function getPriceAnalytics(
  householdId: string,
  period: 'month' | 'quarter' | 'year' = 'month',
): Promise<MedicineSpendingAnalyticsResponse> {
  return apiClient.get<MedicineSpendingAnalyticsResponse>(
    `/households/${householdId}/medicine-prices/analytics?period=${period}`,
  );
}
