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

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

    let content = message.content;
    let modified = false;

    // Feature: Word Mimic
    if (content.toLowerCase().includes('kord')) {
      content = content.replace(/kord/gi, 'Kord(최고존엄)');
      modified = true;
    }

    if (modified) {
      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,
            username: message.member?.displayName || message.author.username,
            avatarURL: message.author.displayAvatarURL(),
          });
          
          if (message.deletable) {
            await message.delete();
          }
        }
      } catch (error) {
        logger.error(`MimicService Error:`, error);
      }
    }
  }
}
