import {IQueryHandler, QueryHandler} from "@nestjs/cqrs";
import {ChatgptRequestQuery} from "../chatgpt-request.command";
import {Promise} from "mongoose";
import {ConfigService} from "@nestjs/config";
import OpenAI from "openai";
import {Logger} from "@nestjs/common";
import {Chat} from "openai/resources";
import ChatCompletion = Chat.ChatCompletion;

@QueryHandler(ChatgptRequestQuery)
export class ChatgtpRequestQueryHandler implements IQueryHandler<ChatgptRequestQuery,ChatCompletion.Choice>{
  private aiClient: OpenAI;
  private readonly logger = new Logger(ChatgtpRequestQueryHandler.name);
  private model: string;

  constructor(private configService: ConfigService) {
    const token = configService.get<string>('OPENAI_TOKEN');
    this.model = configService.get<string>('OPENAI_MODEL');
    this.aiClient= new OpenAI({ apiKey: token})
  }
  async execute(query: ChatgptRequestQuery): Promise<ChatCompletion.Choice> {
    this.logger.verbose(`enter`);
    const data = await this.aiClient.chat.completions.create({
      messages: [...query.payload],
      model: this.model,
    });
    return data.choices[0];
  }

}