import { count } from "drizzle-orm";
import { database } from "@/db";
import { user } from "@/db/schema/auth";
import { libraryFolders } from "@/db/schema/libraries";
import { episodes, movies, series } from "@/db/schema/metadata";
import { t } from "@/lib/trpc";
import { GetStatsOverviewOutput } from "@/models/trpc/stats";
import { authenticationMiddleware } from "../middleware/authentication";

const statsProcedure = t.procedure.use(authenticationMiddleware);

export const statsRouter = t.router({
	getOverview: statsProcedure.output(GetStatsOverviewOutput).query(async () => {
		const [
			usersCount,
			moviesCount,
			seriesCount,
			episodesCount,
			librariesCount,
		] = await Promise.all([
			database.select({ count: count() }).from(user),
			database.select({ count: count() }).from(movies),
			database.select({ count: count() }).from(series),
			database.select({ count: count() }).from(episodes),
			database.select({ count: count() }).from(libraryFolders),
		]);

		return {
			totalUsers: usersCount[0].count,
			totalMovies: moviesCount[0].count,
			totalSeries: seriesCount[0].count,
			totalEpisodes: episodesCount[0].count,
			totalLibraries: librariesCount[0].count,
		};
	}),
});
