import { apiClient } from './api-client';
import type { z } from 'zod/v4';
import type {
  PurchaseResponseSchema,
  PurchaseListResponseSchema,
  CreatePurchaseSchema,
  UpdatePurchaseSchema,
  PurchaseQuerySchema,
} from '@meshitrack/shared';

type PurchaseResponse = z.infer<typeof PurchaseResponseSchema>;
type PurchaseListResponse = z.infer<typeof PurchaseListResponseSchema>;
type CreatePurchaseInput = z.infer<typeof CreatePurchaseSchema>;
type UpdatePurchaseInput = z.infer<typeof UpdatePurchaseSchema>;
type PurchaseQueryInput = z.infer<typeof PurchaseQuerySchema>;

export async function listPurchases(
  householdId: string,
  query?: Partial<PurchaseQueryInput>,
): Promise<PurchaseListResponse> {
  const params = new URLSearchParams();
  if (query?.status) params.set('status', query.status);
  if (query?.storeId) params.set('storeId', query.storeId);
  if (query?.cursor) params.set('cursor', query.cursor);
  if (query?.limit) params.set('limit', String(query.limit));
  const qs = params.toString();
  return apiClient.get<PurchaseListResponse>(
    `/households/${householdId}/purchases${qs ? `?${qs}` : ''}`,
  );
}

export async function getPurchase(householdId: string, id: string): Promise<PurchaseResponse> {
  return apiClient.get<PurchaseResponse>(`/households/${householdId}/purchases/${id}`);
}

export async function createPurchase(
  householdId: string,
  data: CreatePurchaseInput,
): Promise<PurchaseResponse> {
  return apiClient.post<PurchaseResponse>(`/households/${householdId}/purchases`, data);
}

export async function updatePurchase(
  householdId: string,
  id: string,
  data: UpdatePurchaseInput,
): Promise<PurchaseResponse> {
  return apiClient.patch<PurchaseResponse>(`/households/${householdId}/purchases/${id}`, data);
}

export async function receivePurchase(
  householdId: string,
  id: string,
): Promise<{ addedCount: number; priceRecordsCreated: number }> {
  return apiClient.post<{ addedCount: number; priceRecordsCreated: number }>(
    `/households/${householdId}/purchases/${id}/receive`,
    {},
  );
}

export async function deletePurchase(householdId: string, id: string): Promise<PurchaseResponse> {
  return apiClient.delete<PurchaseResponse>(`/households/${householdId}/purchases/${id}`);
}
