import { Client, GatewayIntentBits, Partials } from 'discord.js';
import { saveMessages } from './database.js';

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
  partials: [Partials.Channel],
});

let readyResolve;
const readyPromise = new Promise((resolve) => {
  readyResolve = resolve;
});

client.once('ready', () => {
  console.log(`Discord bot logged in as ${client.user.tag}`);
  readyResolve();
});

client.on('error', (error) => {
  console.error('Discord client error:', error);
});

export async function fetchChannelMessages(channelId, limit = 100) {
  try {
    const channel = await client.channels.fetch(channelId);

    if (!channel.isTextBased()) {
      throw new Error('Channel is not text-based');
    }

    const messages = [];
    let lastMessageId = undefined;

    while (messages.length < limit) {
      const fetchLimit = Math.min(limit - messages.length, 100);
      const options = { limit: fetchLimit };

      if (lastMessageId) {
        options.before = lastMessageId;
      }

      const fetched = await channel.messages.fetch(options);

      if (fetched.size === 0) break;

      for (const [id, msg] of fetched) {
        if (msg.system) continue; // Skip system messages

        messages.push({
          id: msg.id,
          channelId: msg.channelId,
          authorId: msg.author.id,
          authorName: msg.author.username,
          content: msg.content || '',
          createdAt: msg.createdTimestamp,
        });

        lastMessageId = msg.id;
      }

      if (fetched.size < 100) break;
    }

    // Sort by creation date ascending
    messages.sort((a, b) => a.createdAt - b.createdAt);

    if (messages.length > 0) {
      saveMessages(messages);
      console.log(`Fetched and saved ${messages.length} messages from channel ${channelId}`);
    }

    return messages;
  } catch (error) {
    console.error(`Error fetching messages from channel ${channelId}:`, error);
    throw error;
  }
}

export async function login(token) {
  await client.login(token);
  await readyPromise;
}

export { client };
