import { apiClient } from './api-client';
import type { z } from 'zod/v4';
import type {
  CabinetItemResponseSchema,
  CabinetItemListResponseSchema,
  CabinetSummaryResponseSchema,
  CreateCabinetItemInput,
  UpdateCabinetItemInput,
  AdjustQuantityInput,
} from '@meshitrack/shared';

type CabinetItemResponse = z.infer<typeof CabinetItemResponseSchema>;
type CabinetItemListResponse = z.infer<typeof CabinetItemListResponseSchema>;
type CabinetSummaryResponse = z.infer<typeof CabinetSummaryResponseSchema>;

export async function listCabinetItems(
  householdId: string,
  query?: {
    medicineId?: string;
    status?: string;
    expiringWithin?: number;
    cursor?: string;
    limit?: number;
  },
): Promise<CabinetItemListResponse> {
  const params = new URLSearchParams();
  if (query?.medicineId) params.set('medicineId', query.medicineId);
  if (query?.status) params.set('status', query.status);
  if (query?.expiringWithin) params.set('expiringWithin', String(query.expiringWithin));
  if (query?.cursor) params.set('cursor', query.cursor);
  if (query?.limit) params.set('limit', String(query.limit));
  const qs = params.toString();
  return apiClient.get<CabinetItemListResponse>(
    `/households/${householdId}/cabinet${qs ? `?${qs}` : ''}`,
  );
}

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

export async function getCabinetSummary(householdId: string): Promise<CabinetSummaryResponse> {
  return apiClient.get<CabinetSummaryResponse>(`/households/${householdId}/cabinet/summary`);
}

export async function getExpiringSoon(
  householdId: string,
  days = 30,
): Promise<{ data: CabinetItemResponse[] }> {
  return apiClient.get<{ data: CabinetItemResponse[] }>(
    `/households/${householdId}/cabinet/expiring-soon?days=${days}`,
  );
}

export async function createCabinetItem(
  householdId: string,
  data: CreateCabinetItemInput,
): Promise<CabinetItemResponse> {
  return apiClient.post<CabinetItemResponse>(`/households/${householdId}/cabinet`, data);
}

export async function updateCabinetItem(
  householdId: string,
  id: string,
  data: UpdateCabinetItemInput,
): Promise<CabinetItemResponse> {
  return apiClient.patch<CabinetItemResponse>(`/households/${householdId}/cabinet/${id}`, data);
}

export async function adjustCabinetItemQuantity(
  householdId: string,
  id: string,
  data: AdjustQuantityInput,
): Promise<CabinetItemResponse> {
  return apiClient.post<CabinetItemResponse>(
    `/households/${householdId}/cabinet/${id}/adjust`,
    data,
  );
}

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