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

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 interaction.deferReply({ flags: MessageFlags.Ephemeral });

        try {
            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;
            }

            // 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)
            });

            // 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
                });
            }

        } catch (error) {
            console.error("Warn command error:", error);
            await interaction.editReply({
                embeds: [getModerationErrorEmbed("An error occurred while issuing the warning.")]
            });
        }
    }
});
