import { type Message } from 'discord.js';
import { tf } from '@nexumi/shared';
import type { BotContext } from '../../types.js';
import { ensureGuild } from '../../guild.js';
import { getGuildLocale } from '../../i18n.js';

export async function setAfk(
  context: BotContext,
  guildId: string,
  userId: string,
  reason: string | null
): Promise<void> {
  await ensureGuild(context.prisma, guildId);
  await context.prisma.afkStatus.upsert({
    where: { guildId_userId: { guildId, userId } },
    update: { reason },
    create: { guildId, userId, reason }
  });
}

export async function clearAfk(
  context: BotContext,
  guildId: string,
  userId: string
): Promise<{ reason: string | null } | null> {
  const status = await context.prisma.afkStatus.findUnique({
    where: { guildId_userId: { guildId, userId } }
  });
  if (!status) {
    return null;
  }
  await context.prisma.afkStatus.delete({
    where: { guildId_userId: { guildId, userId } }
  });
  return { reason: status.reason };
}

export async function getAfkStatus(
  context: BotContext,
  guildId: string,
  userId: string
): Promise<{ reason: string | null } | null> {
  const status = await context.prisma.afkStatus.findUnique({
    where: { guildId_userId: { guildId, userId } }
  });
  if (!status) {
    return null;
  }
  return { reason: status.reason };
}

export function registerAfkEvents(context: BotContext): void {
  context.client.on('messageCreate', async (message: Message) => {
    if (message.author.bot || !message.guildId) {
      return;
    }

    try {
      const locale = await getGuildLocale(context.prisma, message.guildId);

      const cleared = await clearAfk(context, message.guildId, message.author.id);
      if (cleared) {
        await message.reply({
          content: tf(locale, 'utility.afk.welcomeBack', {
            reason: cleared.reason ?? '—'
          }),
          allowedMentions: { repliedUser: false }
        }).catch(() => undefined);
      }

      const mentions = message.mentions.users.filter((u) => !u.bot && u.id !== message.author.id);
      for (const [, user] of mentions) {
        const afk = await getAfkStatus(context, message.guildId, user.id);
        if (!afk) {
          continue;
        }
        await message.reply({
          content: tf(locale, 'utility.afk.mention', {
            user: `<@${user.id}>`,
            reason: afk.reason ?? '—'
          }),
          allowedMentions: { users: [user.id] }
        }).catch(() => undefined);
      }
    } catch {
      // Non-critical
    }
  });
}
