import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { scheduleAlertEngineAfterDataCollectors } from "../services/alert-collector-hooks.js"
import { refreshScheduler } from "../services/scheduler.js"
import {
  collectServersRestPingOnce,
  getServersApiPingSettings,
  getServersRestPingCollectorState,
  updateServersApiPingSettings,
} from "../services/servers-rest-ping-collector.js"

const serversApiPingRoutes: FastifyPluginAsyncZod = async (app) => {
  app.get("/servers-api-ping/settings", async (_req, reply) => {
    const settings = getServersApiPingSettings()
    const state = getServersRestPingCollectorState()
    return reply.send({
      enabled: settings.enabled,
      intervalSec: settings.intervalSec,
      lastCollectedAt: settings.lastCollectedAt ?? null,
      lastDurationMs: settings.lastDurationMs ?? null,
      lastError: settings.lastError || null,
      collectorRunning: state.running,
    })
  })

  app.put("/servers-api-ping/settings", async (req, reply) => {
    const body = req.body as {
      enabled?: boolean
      intervalSec?: number | string
    }
    const intervalSec =
      body.intervalSec == null ? undefined : Math.max(10, Number.parseInt(String(body.intervalSec), 10) || 120)
    const updated = updateServersApiPingSettings({
      enabled: body.enabled,
      intervalSec,
    })
    refreshScheduler()
    return reply.send({
      ok: true,
      settings: {
        enabled: updated.enabled,
        intervalSec: updated.intervalSec,
        lastCollectedAt: updated.lastCollectedAt ?? null,
        lastDurationMs: updated.lastDurationMs ?? null,
        lastError: updated.lastError || null,
      },
    })
  })

  app.post("/servers-api-ping/collect-now", async (_req, reply) => {
    await collectServersRestPingOnce()
    scheduleAlertEngineAfterDataCollectors()
    const row = getServersApiPingSettings()
    return reply.send({
      ok: true,
      lastCollectedAt: row.lastCollectedAt ?? null,
      lastDurationMs: row.lastDurationMs ?? null,
      lastError: row.lastError || null,
    })
  })
}

export default serversApiPingRoutes
