import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { count } from "drizzle-orm"
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"

function tableCount(table: typeof servers | typeof filterRules | typeof uptimeProbes | typeof uptimeSpeedProbes | typeof recursiveRoutes): number {
  return db.select({ n: count() }).from(table).all()[0]?.n ?? 0
}

const sidebarCountsRoutes: FastifyPluginAsyncZod = async (app) => {
  app.get("/sidebar-counts", async (_req, reply) => {
    const serversTotal = tableCount(servers)
    const filterRulesTotal = tableCount(filterRules)
    const uptimeProbesTotal = tableCount(uptimeProbes)
    const uptimeSpeedProbesTotal = tableCount(uptimeSpeedProbes)
    const recursiveRoutesTotal = tableCount(recursiveRoutes)
    const [certificatesTotal, wireguardTotal] = await Promise.all([
      listCertificatesFromServers().then((res) => res.certificates.length),
      countWireGuardInterfaces().catch(() => 0),
    ])
    const usersTotal = 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
