import { Injectable, Inject, Logger } from '@nestjs/common';
import {
  AI_AGENT_CLIENT,
  IAiAgentClient,
  AgentChatRequest,
} from '../../domain/ports/ai-agent.client.interface';
import { ChatRequestDto, ChatResponseDto } from '../../interface/http/dto/chat.dto';

@Injectable()
export class AiChatService {
  private readonly logger = new Logger(AiChatService.name);

  constructor(
    @Inject(AI_AGENT_CLIENT) private readonly agentClient: IAiAgentClient,
  ) {}

  async chat(req: ChatRequestDto): Promise<ChatResponseDto> {
    const agentReq: AgentChatRequest = {
      userId: req.userId,
      message: req.message,
      sessionId: req.sessionId,
      context: req.context,
    };

    try {
      const response = await this.agentClient.chat(agentReq);
      return {
        reply: response.reply || 'I apologize, I could not process your request.',
        sessionId: response.sessionId,
        suggestions: response.suggestions,
      };
    } catch (error) {
      this.logger.error(`Chat failed: ${error.message}`);
      // Fallback response when AI agent is unavailable
      return {
        reply: 'Our AI assistant is currently unavailable. Please try again later or contact support.',
        sessionId: req.sessionId || `session-${Date.now()}`,
        suggestions: ['Contact Support', 'View FAQ'],
      };
    }
  }
}
