import { z } from "zod"

export const eventLevelSchema = z.enum(["critical", "warning", "info"])

export const eventSourceModuleSchema = z.enum([
  "scheduler",
  "backups",
  "filters",
  "traffic",
  "alerts",
  "certificates",
  "system",
])

export const eventItemSchema = z.object({
  id: z.string().min(1),
  createdAt: z.string(),
  level: eventLevelSchema,
  eventType: z.string().min(1),
  sourceModule: eventSourceModuleSchema,
  title: z.string().min(1),
  message: z.string().min(1),
  entityType: z.union([z.string(), z.null()]),
  entityId: z.union([z.string(), z.null()]),
  payload: z.record(z.string(), z.unknown()).default({}),
})

export const eventListSchema = z.array(eventItemSchema)

export const listEventsQuerySchema = z.object({
  limit: z.coerce.number().int().min(1).max(100).default(20),
  level: eventLevelSchema.optional(),
  sourceModule: eventSourceModuleSchema.optional(),
  from: z.string().optional(),
  to: z.string().optional(),
})

export const appendEventSchema = z.object({
  level: eventLevelSchema,
  eventType: z.string().min(1),
  sourceModule: eventSourceModuleSchema,
  title: z.string().min(1),
  message: z.string().min(1),
  entityType: z.string().optional(),
  entityId: z.string().optional(),
  payload: z.record(z.string(), z.unknown()).optional(),
  createdAt: z.string().optional(),
})

export const appendEventsSchema = z.object({
  events: z.array(appendEventSchema).min(1).max(200),
})

export type EventLevel = z.infer<typeof eventLevelSchema>
export type EventSourceModule = z.infer<typeof eventSourceModuleSchema>
export type EventItem = z.infer<typeof eventItemSchema>
export type ListEventsQuery = z.infer<typeof listEventsQuerySchema>
export type AppendEventBody = z.infer<typeof appendEventSchema>
export type AppendEventsBody = z.infer<typeof appendEventsSchema>
