const AdapterBase = require('./adapter-base');

class SlackAdapter extends AdapterBase {
  constructor({ ownerNames = [] } = {}) {
    super('slack');
    this.ownerNames = ownerNames.map(n => n.toLowerCase());
    this._pendingMessages = [];
  }

  feed(messages) {
    this._pendingMessages.push(...messages);
  }

  async poll(since) {
    const memories = this._pendingMessages
      .map(msg => this.normalize(msg))
      .filter(m => m !== null);

    this._pendingMessages = [];

    if (since) {
      const sinceDate = new Date(since);
      return memories.filter(m => new Date(m.timestamp) > sinceDate);
    }

    return memories;
  }

  normalize(rawData) {
    if (!rawData) return null;
    const { sender, text, channel, ts, permalink, thread_ts, timestamp } = rawData;

    if (!text || !text.trim()) {
      return null;
    }

    const isOwner = sender
      ? this.ownerNames.includes(sender.toLowerCase())
      : false;

    return {
      source: 'slack',
      source_id: ts || `generated-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
      source_channel: channel,
      memory_type: isOwner ? 'message_sent' : 'message_received',
      direction: isOwner ? 'outbound' : 'inbound',
      participants: sender ? JSON.stringify([sender]) : null,
      subject: thread_ts ? `thread:${thread_ts}` : null,
      content: text.trim(),
      metadata: JSON.stringify({ permalink, thread_ts }),
      timestamp: timestamp || new Date().toISOString(),
    };
  }
}

module.exports = SlackAdapter;
