import type { PrismaClient } from '@prisma/client';
import { ensureGuild } from '../../guild.js';

export function utcDayStart(date = new Date()): Date {
  return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
}

export function voiceSessionKey(guildId: string, userId: string): string {
  return `stats:voice:${guildId}:${userId}`;
}

export async function incrementMessageActivity(
  prisma: PrismaClient,
  guildId: string,
  userId: string,
  channelId: string
): Promise<void> {
  await ensureGuild(prisma, guildId);
  const day = utcDayStart();

  await prisma.activityStat.upsert({
    where: {
      guildId_userId_channelId_day: {
        guildId,
        userId,
        channelId,
        day
      }
    },
    update: {
      messageCount: { increment: 1 }
    },
    create: {
      guildId,
      userId,
      channelId,
      day,
      messageCount: 1,
      voiceMinutes: 0
    }
  });
}

export async function addVoiceMinutes(
  prisma: PrismaClient,
  guildId: string,
  userId: string,
  channelId: string,
  joinedAtMs: number
): Promise<void> {
  const minutes = Math.floor((Date.now() - joinedAtMs) / 60_000);
  if (minutes <= 0) {
    return;
  }

  await ensureGuild(prisma, guildId);
  const day = utcDayStart();

  await prisma.activityStat.upsert({
    where: {
      guildId_userId_channelId_day: {
        guildId,
        userId,
        channelId,
        day
      }
    },
    update: {
      voiceMinutes: { increment: minutes }
    },
    create: {
      guildId,
      userId,
      channelId,
      day,
      messageCount: 0,
      voiceMinutes: minutes
    }
  });
}
