import { createCommand } from "@shared/lib/utils";
import { SlashCommandBuilder, PermissionFlagsBits, MessageFlags } from "discord.js";
import { moderationService } from "@shared/modules/moderation/moderation.service";
import {
    getWarnSuccessEmbed,
    getModerationErrorEmbed,
} from "@/modules/moderation/moderation.view";
import { getGuildConfig } from "@shared/lib/config";
import { withCommandErrorHandling } from "@lib/commandUtils";

export const warn = createCommand({
    data: new SlashCommandBuilder()
        .setName("warn")
        .setDescription("Issue a warning to a user")
        .addUserOption(option =>
            option
                .setName("user")
                .setDescription("The user to warn")
                .setRequired(true)
        )
        .addStringOption(option =>
            option
                .setName("reason")
                .setDescription("Reason for the warning")
                .setRequired(true)
                .setMaxLength(1000)
        )
        .setDefaultMemberPermissions(PermissionFlagsBits.Administrator),

    execute: async (interaction) => {
        await withCommandErrorHandling(
            interaction,
            async () => {
                const targetUser = interaction.options.getUser("user", true);
                const reason = interaction.options.getString("reason", true);

                // Don't allow warning bots
                if (targetUser.bot) {
                    await interaction.editReply({
                        embeds: [getModerationErrorEmbed("You cannot warn bots.")]
                    });
                    return;
                }

                // Don't allow self-warnings
                if (targetUser.id === interaction.user.id) {
                    await interaction.editReply({
                        embeds: [getModerationErrorEmbed("You cannot warn yourself.")]
                    });
                    return;
                }

                // Fetch guild config for moderation settings
                const guildConfig = await getGuildConfig(interaction.guildId!);

                // Issue the warning via service
                const { moderationCase, warningCount, autoTimeoutIssued } = await moderationService.issueWarning({
                    userId: targetUser.id,
                    username: targetUser.username,
                    moderatorId: interaction.user.id,
                    moderatorName: interaction.user.username,
                    reason,
                    guildName: interaction.guild?.name || undefined,
                    dmTarget: targetUser,
                    timeoutTarget: await interaction.guild?.members.fetch(targetUser.id),
                    config: {
                        dmOnWarn: guildConfig.moderation?.cases?.dmOnWarn,
                        autoTimeoutThreshold: guildConfig.moderation?.cases?.autoTimeoutThreshold,
                    },
                });

                // Send success message to moderator
                await interaction.editReply({
                    embeds: [getWarnSuccessEmbed(moderationCase.caseId, targetUser.username, reason)]
                });

                // Follow up if auto-timeout was issued
                if (autoTimeoutIssued) {
                    await interaction.followUp({
                        embeds: [getModerationErrorEmbed(
                            `⚠️ User has reached ${warningCount} warnings and has been automatically timed out for 24 hours.`
                        )],
                        flags: MessageFlags.Ephemeral
                    });
                }
            },
            { ephemeral: true }
        );
    }
});
