import { PermissionFlagsBits } from 'discord.js';
import { t, tf } from '@nexumi/shared';
import type { SlashCommand } from '../../types.js';
import { getGuildLocale } from '../../i18n.js';
import { requirePermission } from '../../permissions.js';
import { automodStatusCommandData } from './command-definitions.js';
import { getAutoModConfig, getEnabledAutoModRules } from './service.js';

const automodCommand: SlashCommand = {
  data: automodStatusCommandData,
  async execute(interaction, context) {
    const locale = await getGuildLocale(context.prisma, interaction.guildId);
    if (!interaction.inGuild()) {
      await interaction.reply({ content: t(locale, 'generic.guildOnly'), ephemeral: true });
      return;
    }
    if (!(await requirePermission(interaction, PermissionFlagsBits.ManageGuild, locale))) {
      return;
    }

    const sub = interaction.options.getSubcommand();
    if (sub !== 'status') {
      return;
    }

    const guildId = interaction.guildId!;
    const config = await getAutoModConfig(context.prisma, guildId);
    const rules = await getEnabledAutoModRules(context.prisma, guildId);

    const lines = rules.map((rule) =>
      tf(locale, 'automod.status.ruleLine', {
        type: rule.ruleType,
        action: rule.action
      })
    );

    const body = [
      tf(locale, 'automod.status.header', {
        enabled: config.enabled ? t(locale, 'automod.status.yes') : t(locale, 'automod.status.no'),
        antiRaid: config.antiRaidEnabled
          ? t(locale, 'automod.status.yes')
          : t(locale, 'automod.status.no'),
        antiNuke: config.antiNukeEnabled
          ? t(locale, 'automod.status.yes')
          : t(locale, 'automod.status.no'),
        lockdown: config.lockdownActive
          ? t(locale, 'automod.status.yes')
          : t(locale, 'automod.status.no')
      }),
      lines.length > 0 ? lines.join('\n') : t(locale, 'automod.status.noRules')
    ].join('\n\n');

    await interaction.reply({ content: body, ephemeral: true });
  }
};

export const automodCommands: SlashCommand[] = [automodCommand];
