import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { appendEventsSchema, listEventsQuerySchema } from "@mmapp/contracts/events"
import { appendEvents, readEvents } from "../modules/events/service/events-service.js"

const eventsRoutes: FastifyPluginAsyncZod = async (app) => {
  app.get("/events", async (req, reply) => {
    const parsed = listEventsQuerySchema.safeParse(req.query ?? {})
    if (!parsed.success) {
      return reply.status(400).send({ error: "Некорректные параметры запроса", details: parsed.error.flatten() })
    }
    return reply.send({ events: readEvents(parsed.data) })
  })

  app.post("/events/batch", async (req, reply) => {
    const parsed = appendEventsSchema.safeParse(req.body)
    if (!parsed.success) {
      return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
    }
    appendEvents(parsed.data.events)
    return reply.status(201).send({ ok: true, inserted: parsed.data.events.length })
  })
}

export default eventsRoutes
