import { Message, TextChannel, PermissionFlagsBits } from 'discord.js';
import { WebhookService } from './WebhookService';
import { logger } from '../utils/logger';

export class BigEmojiService {
  public static async handleMessage(message: Message) {
    if (message.author.bot) return;
    if (!(message.channel instanceof TextChannel)) return;

    const content = message.content;
    
    // Check if message is exactly one custom discord emoji
    const customEmojiRegex = /^<a?:.+:(\d+)>$/i;
    const match = content.match(customEmojiRegex);
    
    if (match) {
      const emojiId = match[1];
      const isAnimated = content.startsWith('<a:');
      const ext = isAnimated ? 'gif' : 'png';
      const emojiUrl = `https://cdn.discordapp.com/emojis/${emojiId}.${ext}?size=256`;

      try {
        const me = message.guild?.members.me;
        if (!me?.permissionsIn(message.channel).has(PermissionFlagsBits.ManageWebhooks)) {
          return;
        }

        const webhookClient = await WebhookService.getWebhookClient(message.channel);
        if (webhookClient) {
          await webhookClient.send({
            content: emojiUrl,
            username: message.member?.displayName || message.author.username,
            avatarURL: message.author.displayAvatarURL(),
          });
          
          if (message.deletable) {
            await message.delete();
          }
        }
      } catch (error) {
        logger.error(`BigEmojiService Error:`, error);
      }
    }
  }
}
