import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
import { Message } from 'src/chatbot/dtos/dialog-message.dto';
import { ChatbotResponseDto, UserMessageDto } from 'src/chatbot/dtos/user-message.dto';

@Injectable()
export class ChatbotService {
    constructor(private readonly httpService: HttpService) { }
    sessionId: string = 'testing';

    async pingExternalApi(body: UserMessageDto, email: string): Promise<Message> {
        try {
            const response = await firstValueFrom(this.httpService.post(
                'https://n8nai.targo.ca/webhook/chatty-Mcbot',
                {
                    userInput: body.userInput,
                    userId: email,
                    sessionId: this.sessionId,
                    pageContext: body.pageContext ?? undefined
                }
            ))as ChatbotResponseDto;

            if (!response.data) 
                return {
                    text: 'chatbot.error.NO_DATA_RECEIVED',
                    sent: false,
                }

            if (!response.data[0].output) 
                return {
                    text: 'chatbot.error.NO_OUTPUT_RECEIVED',
                    sent: false,
                }

            return {
                text: response.data[0].output,
                sent: false,
            };
        } catch (error) {
            console.error(error);

            return {
                text: 'chatbot.error.GENERIC_RESPONSE_ERROR',
                sent: false,
            }
        }
    }
}
