import type { ActivityStatSummary } from '@nexumi/shared';
import { prisma } from './prisma';

const SUMMARY_WINDOW_DAYS = 7;

/**
 * Aggregates `ActivityStat` rows (written by the bot's leveling/stats
 * modules) for the last {@link SUMMARY_WINDOW_DAYS} days into totals shown
 * on the guild overview page.
 */
export async function getActivitySummary(guildId: string): Promise<ActivityStatSummary> {
  const since = new Date(Date.now() - SUMMARY_WINDOW_DAYS * 24 * 60 * 60 * 1000);

  const [aggregate, activeUsers] = await Promise.all([
    prisma.activityStat.aggregate({
      where: { guildId, day: { gte: since } },
      _sum: { messageCount: true, voiceMinutes: true }
    }),
    prisma.activityStat.findMany({
      where: { guildId, day: { gte: since } },
      distinct: ['userId'],
      select: { userId: true }
    })
  ]);

  return {
    messageCount: aggregate._sum.messageCount ?? 0,
    voiceMinutes: aggregate._sum.voiceMinutes ?? 0,
    activeUserCount: activeUsers.length
  };
}
