import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { db } from "../db/index.js"
import {
  filterRules,
  recursiveRoutes,
  servers,
  uptimeProbes,
  uptimeSpeedProbes,
} from "../db/schema.js"

const sidebarCountsRoutes: FastifyPluginAsyncZod = async (app) => {
  app.get("/sidebar-counts", async (_req, reply) => {
    const [
      serversTotal,
      filterRulesTotal,
      uptimeProbesTotal,
      uptimeSpeedProbesTotal,
      recursiveRoutesTotal,
    ] = [
      db.select().from(servers).all().length,
      db.select().from(filterRules).all().length,
      db.select().from(uptimeProbes).all().length,
      db.select().from(uptimeSpeedProbes).all().length,
      db.select().from(recursiveRoutes).all().length,
    ]

    return reply.send({
      servers: serversTotal,
      filterRules: filterRulesTotal,
      uptimeProbes: uptimeProbesTotal,
      uptimeSpeedProbes: uptimeSpeedProbesTotal,
      monitoringItems: uptimeProbesTotal + uptimeSpeedProbesTotal,
      recursiveRoutes: recursiveRoutesTotal,
    })
  })
}

export default sidebarCountsRoutes
