import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { listCertificatesFromServers } from "../services/certificates-service.js"
import { countWireGuardInterfaces } from "../services/wireguard-live.js"
import { db } from "../db/index.js"
import {
  filterRules,
  recursiveRoutes,
  servers,
  uptimeProbes,
  uptimeSpeedProbes,
} from "../db/schema.js"
import { listUsers } from "../modules/users/service/users-service.js"

const sidebarCountsRoutes: FastifyPluginAsyncZod = async (app) => {
  app.get("/sidebar-counts", async (_req, reply) => {
    const [
      serversTotal,
      filterRulesTotal,
      uptimeProbesTotal,
      uptimeSpeedProbesTotal,
      recursiveRoutesTotal,
      certificatesTotal,
      wireguardTotal,
      usersTotal,
    ] = await Promise.all([
      Promise.resolve(db.select().from(servers).all().length),
      Promise.resolve(db.select().from(filterRules).all().length),
      Promise.resolve(db.select().from(uptimeProbes).all().length),
      Promise.resolve(db.select().from(uptimeSpeedProbes).all().length),
      Promise.resolve(db.select().from(recursiveRoutes).all().length),
      listCertificatesFromServers().then((res) => res.certificates.length),
      countWireGuardInterfaces().catch(() => 0),
      Promise.resolve(listUsers().length),
    ])

    return reply.send({
      servers: serversTotal,
      filterRules: filterRulesTotal,
      uptimeProbes: uptimeProbesTotal,
      uptimeSpeedProbes: uptimeSpeedProbesTotal,
      monitoringItems: uptimeProbesTotal + uptimeSpeedProbesTotal,
      recursiveRoutes: recursiveRoutesTotal,
      certificates: certificatesTotal,
      wireguard: wireguardTotal,
      users: usersTotal,
    })
  })
}

export default sidebarCountsRoutes
