import type { GatewayRequest, OutboundMessage } from '../protocol.js';
import { makeError, makeResponse, ErrorCode } from '../protocol.js';
import type { SessionManager } from '../../session/manager.js';

export interface HistoryHandlerDeps {
  sessionManager: SessionManager;
}

export function createHistoryHandlers(deps: HistoryHandlerDeps) {
  return {
    'history.search': async (request: GatewayRequest): Promise<OutboundMessage> => {
      const params = request.params as { query?: string; sessionId?: string; limit?: number } | undefined;
      if (!params?.query) {
        return makeError(request.id, ErrorCode.InvalidRequest, 'query is required');
      }

      const results = deps.sessionManager.searchHistory(params.query, {
        sessionId: params.sessionId,
        limit: params.limit,
      });

      return makeResponse(request.id, { results });
    },

    'history.reindex': async (request: GatewayRequest): Promise<OutboundMessage> => {
      const reindexed = deps.sessionManager.reindexHistory();
      return makeResponse(request.id, { reindexed });
    },
  };
}
