import { prisma } from "@repo/db";
import promClient from "prom-client";

export const promRegister = new promClient.Registry();
promClient.collectDefaultMetrics({ register: promRegister });

export const connectedPilots = new promClient.Gauge({
	name: "connected_pilots",
	help: "Counts connected pilots",
	registers: [promRegister],
	collect: async () => {
		const count = await prisma.connectedAircraft.count({
			where: {
				logoutTime: null,
			},
		});
		connectedPilots.set(count);
	},
});

export const connectedDispatcher = new promClient.Gauge({
	name: "connected_dispatcher",
	help: "Counts connected dispatchers",
	registers: [promRegister],
	collect: async () => {
		const count = await prisma.connectedDispatcher.count({
			where: {
				logoutTime: null,
			},
		});
		connectedDispatcher.set(count);
	},
});

export const totalUsers = new promClient.Gauge({
	name: "total_users",
	help: "Counts total users",
	registers: [promRegister],
	collect: async () => {
		const count = await prisma.user.count();
		totalUsers.set(count);
	},
});

export const pilotUsers = new promClient.Gauge({
	name: "pilot_users",
	help: "Counts pilot users",
	registers: [promRegister],
	collect: async () => {
		const count = await prisma.user.count({
			where: {
				permissions: {
					has: "PILOT",
				},
			},
		});
		pilotUsers.set(count);
	},
});

export const dispatcherUsers = new promClient.Gauge({
	name: "dispatcher_users",
	help: "Counts dispatcher users",
	registers: [promRegister],
	collect: async () => {
		const count = await prisma.user.count({
			where: {
				permissions: {
					has: "DISPO",
				},
			},
		});
		dispatcherUsers.set(count);
	},
});

promRegister.registerMetric(pilotUsers);
promRegister.registerMetric(dispatcherUsers);
promRegister.registerMetric(totalUsers);
promRegister.registerMetric(connectedPilots);
promRegister.registerMetric(connectedDispatcher);
