import { apiClient } from './api-client';
import type { z } from 'zod/v4';
import type {
  PriceRecordResponseSchema,
  PriceHistoryResponseSchema,
  FoodStoreComparisonResponseSchema,
  FoodSpendingAnalyticsResponseSchema,
  CreatePriceRecordSchema,
  BulkPriceRecordInputSchema,
} from '@meshitrack/shared';

type PriceRecordResponse = z.infer<typeof PriceRecordResponseSchema>;
type PriceHistoryResponse = z.infer<typeof PriceHistoryResponseSchema>;
type FoodStoreComparisonResponse = z.infer<typeof FoodStoreComparisonResponseSchema>;
type FoodSpendingAnalyticsResponse = z.infer<typeof FoodSpendingAnalyticsResponseSchema>;
type CreatePriceRecordInput = z.infer<typeof CreatePriceRecordSchema>;
type BulkPriceRecordInput = z.infer<typeof BulkPriceRecordInputSchema>;

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

export async function recordBulkPrices(
  householdId: string,
  data: BulkPriceRecordInput
): Promise<PriceRecordResponse[]> {
  return apiClient.post<PriceRecordResponse[]>(`/households/${householdId}/prices/bulk`, data);
}

export async function getPriceHistory(
  householdId: string,
  productId: string,
  query?: {
    storeId?: string;
    startDate?: string;
    endDate?: string;
    cursor?: string;
    limit?: number;
  }
): Promise<PriceHistoryResponse> {
  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<PriceHistoryResponse>(
    `/households/${householdId}/prices/history/${productId}${qs ? `?${qs}` : ''}`
  );
}

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

export async function getPriceAnalytics(
  householdId: string
): Promise<FoodSpendingAnalyticsResponse> {
  return apiClient.get<FoodSpendingAnalyticsResponse>(
    `/households/${householdId}/prices/analytics`
  );
}
