import { TextChannel, WebhookClient } from 'discord.js';
import { logger } from '../utils/logger';
import { cache } from '../cache';

export class WebhookService {
  private static readonly MAX_WEBHOOKS = 10;
  private static readonly WEBHOOK_NAME = 'Kord Mimic Webhook';

  public static async getWebhookClient(channel: TextChannel): Promise<WebhookClient | null> {
    try {
      // 1. Check cache
      const cachedData = await cache.get(`webhook:${channel.id}`);
      if (cachedData) {
        const { id, token } = JSON.parse(cachedData);
        return new WebhookClient({ id, token });
      }

      // 2. Fetch from Discord API
      const webhooks = await channel.fetchWebhooks();
      let kordWebhook = webhooks.find(wh => wh.name === this.WEBHOOK_NAME && wh.token !== null);

      if (!kordWebhook) {
        if (webhooks.size >= this.MAX_WEBHOOKS) {
          // If we hit limits, delete the oldest webhook
          const oldestWebhook = webhooks.last();
          if (oldestWebhook) {
            await oldestWebhook.delete('Hit max webhook limit for Kord');
            logger.warn(`Deleted oldest webhook in channel ${channel.id}`);
          } else {
            logger.error(`Webhook limits reached in ${channel.id} but no webhook could be deleted.`);
            return null;
          }
        }

        kordWebhook = await channel.createWebhook({
          name: this.WEBHOOK_NAME,
          avatar: channel.client.user?.displayAvatarURL(),
          reason: 'Webhook needed for Kord Mimic & Prank feature',
        });
        logger.info(`Created new webhook for channel ${channel.id}`);
      }

      // 3. Save to cache (expire in 1 day to ensure token freshness)
      if (kordWebhook.token) {
        await cache.set(`webhook:${channel.id}`, JSON.stringify({ id: kordWebhook.id, token: kordWebhook.token }), {
          exSeconds: 86400,
        });
        return new WebhookClient({ id: kordWebhook.id, token: kordWebhook.token });
      }

      return null;
    } catch (error) {
      logger.error(`WebhookService Error on channel ${channel.id}:`, error);
      return null;
    }
  }
}
