import { randomUUID } from "node:crypto"
import {
  appendEventSchema,
  listEventsQuerySchema,
  type AppendEventBody,
  type EventItem,
  type ListEventsQuery,
} from "@mmapp/contracts/events"
import { insertEventsBatch, listEvents, type EventInsertInput } from "../repository/events-repository.js"

function normalizeEventInput(input: AppendEventBody): EventInsertInput {
  return {
    id: randomUUID(),
    createdAt: input.createdAt ?? new Date().toISOString(),
    level: input.level,
    eventType: input.eventType.trim(),
    sourceModule: input.sourceModule,
    title: input.title.trim(),
    message: input.message.trim(),
    entityType: input.entityType?.trim() || undefined,
    entityId: input.entityId?.trim() || undefined,
    payload: input.payload ?? {},
  }
}

export function appendEvent(input: AppendEventBody) {
  const parsed = appendEventSchema.parse(input)
  insertEventsBatch([normalizeEventInput(parsed)])
}

export function appendEvents(inputs: AppendEventBody[]) {
  const rows = inputs.map((entry) => normalizeEventInput(appendEventSchema.parse(entry)))
  insertEventsBatch(rows)
}

export function readEvents(query: Partial<ListEventsQuery>): EventItem[] {
  const parsed = listEventsQuerySchema.parse(query)
  return listEvents(parsed)
}
