import { db } from "@minmon/db";
import { domain, note, server, service } from "@minmon/db";
import { count, desc, eq, inArray } from "drizzle-orm";

import { protectedProcedure, router } from "../index";

export const dashboardRouter = router({
  summary: protectedProcedure.query(async () => {
    const [
      serverCount,
      serviceCount,
      domainCount,
      inactiveServices,
      domainStatuses,
      recentNotes,
      servicesWithServer,
    ] = await Promise.all([
      db.select({ count: count() }).from(server),
      db.select({ count: count() }).from(service),
      db.select({ count: count() }).from(domain),
      db
        .select({ count: count() })
        .from(service)
        .where(inArray(service.status, ["down", "maintenance"])),
      db
        .select({
          status: domain.resolutionStatus,
        })
        .from(domain),
      db
        .select({
          id: note.id,
          title: note.title,
          category: note.category,
          updatedAt: note.updatedAt,
          serverId: note.serverId,
        })
        .from(note)
        .orderBy(desc(note.updatedAt))
        .limit(5),
      db
        .select({
          id: service.id,
          name: service.name,
          status: service.status,
          serverName: server.name,
        })
        .from(service)
        .innerJoin(server, eq(service.serverId, server.id))
        .where(inArray(service.status, ["down", "maintenance"]))
        .orderBy(desc(service.updatedAt))
        .limit(5),
    ]);

    const domainsWithMatchIp = domainStatuses.filter((item) => item.status === "MATCH").length;
    const domainsWithMismatchIp = domainStatuses.filter((item) => item.status === "MISMATCH").length;
    const domainsUnresolved = domainStatuses.filter((item) => item.status === "UNRESOLVED").length;

    return {
      totals: {
        servers: serverCount[0]?.count ?? 0,
        services: serviceCount[0]?.count ?? 0,
        domains: domainCount[0]?.count ?? 0,
      },
      domainChecks: {
        match: domainsWithMatchIp,
        mismatch: domainsWithMismatchIp,
        unresolved: domainsUnresolved,
      },
      inactiveServices: inactiveServices[0]?.count ?? 0,
      recentNotes,
      recentServiceIssues: servicesWithServer,
    };
  }),
});
