import type { FastifyBaseLogger } from 'fastify';
import type { ConversationStore } from '../harness/memory/conversation-store.js';
import type { BlobStore, StoredBlob } from '../harness/memory/blob-store.js';

export interface EnrichedMessage {
  id: string;
  userId: string;
  sessionId: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: number; // microseconds
  files: StoredBlob[];
}

/**
 * Generic conversation history service.
 *
 * Combines text messages (ConversationStore) with binary blobs (BlobStore)
 * into enriched message records. Used by:
 * - WebSocket handler: replay history on reconnect
 * - Future admin panel: conversation browser
 */
export class ConversationService {
  constructor(
    private conversationStore: ConversationStore,
    private blobStore: BlobStore,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    _logger: FastifyBaseLogger
  ) {}

  async getHistory(
    userId: string,
    sessionId: string,
    limit = 50,
    channelType = 'websocket'
  ): Promise<EnrichedMessage[]> {
    const messages = await this.conversationStore.getFullHistory(userId, sessionId, limit, channelType);
    const chatMessages = messages.filter(m => m.role === 'user' || m.role === 'assistant');

    return Promise.all(
      chatMessages.map(async (m) => {
        const blobRefs = m.metadata?.blobs as Array<{ id: string; mimeType: string; caption?: string }> | undefined;
        const files = blobRefs?.length
          ? await this.blobStore.getBlobsByIds(userId, sessionId, blobRefs.map(b => b.id))
          : [];

        return {
          id: m.id,
          userId: m.userId,
          sessionId: m.sessionId,
          role: m.role as 'user' | 'assistant',
          content: m.content,
          timestamp: m.timestamp,
          files,
        };
      })
    );
  }
}
