import {
  eventListSchema,
  listEventsQuerySchema,
  type EventItem,
  type ListEventsQuery,
} from "@mmapp/contracts/events"
import { requestJson } from "@/shared/api/http-client"

type ListEventsResponse = {
  events: unknown
}

export async function listEvents(
  baseUrl: string,
  query: Partial<ListEventsQuery> = {},
): Promise<EventItem[]> {
  const parsedQuery = listEventsQuerySchema.parse(query)
  const search = new URLSearchParams()
  search.set("limit", String(parsedQuery.limit))
  if (parsedQuery.level) search.set("level", parsedQuery.level)
  if (parsedQuery.sourceModule) search.set("sourceModule", parsedQuery.sourceModule)
  if (parsedQuery.from) search.set("from", parsedQuery.from)
  if (parsedQuery.to) search.set("to", parsedQuery.to)
  const path = `/api/events?${search.toString()}`
  const payload = await requestJson<ListEventsResponse>(baseUrl, path)
  return eventListSchema.parse(payload.events)
}
