import { apiClient } from './api-client';
import type { z } from 'zod/v4';
import type {
  OrganizerFillListResponseSchema,
  OrganizerFillResponseSchema,
  OrganizerPreviewResponseSchema,
  OrganizerFillSchema,
  OrganizerPreviewSchema,
} from '@meshitrack/shared';

type OrganizerFillListResponse = z.infer<typeof OrganizerFillListResponseSchema>;
type OrganizerFillResponse = z.infer<typeof OrganizerFillResponseSchema>;
type OrganizerPreviewResponse = z.infer<typeof OrganizerPreviewResponseSchema>;
type OrganizerFillInput = z.infer<typeof OrganizerFillSchema>;
type OrganizerPreviewInput = z.infer<typeof OrganizerPreviewSchema>;

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

export async function getFill(householdId: string, id: string): Promise<OrganizerFillResponse> {
  return apiClient.get<OrganizerFillResponse>(`/households/${householdId}/organizer/fills/${id}`);
}

export async function previewFill(
  householdId: string,
  data: OrganizerPreviewInput,
): Promise<OrganizerPreviewResponse> {
  return apiClient.post<OrganizerPreviewResponse>(
    `/households/${householdId}/organizer/preview`,
    data,
  );
}

export async function executeFill(
  householdId: string,
  data: OrganizerFillInput,
): Promise<OrganizerFillResponse> {
  return apiClient.post<OrganizerFillResponse>(`/households/${householdId}/organizer/fill`, data);
}

export async function undoFill(
  householdId: string,
  fillId: string,
): Promise<OrganizerFillResponse> {
  return apiClient.post<OrganizerFillResponse>(
    `/households/${householdId}/organizer/fills/${fillId}/undo`,
    {},
  );
}
