import type { IExecuteFunctions } from 'n8n-workflow';
import { NodeConnectionType } from 'n8n-workflow';
import type { INodeExecutionData, INodeType, INodeTypeDescription } from 'n8n-workflow';

export class QfoxAi implements INodeType {
  description: INodeTypeDescription = {
    displayName: 'QFOXAI',
    name: 'qfoxAi',
    icon: 'file:qfoxai.svg',
    group: ['transform'],
    version: 1,
    description: 'Send prompts to the QFOXAI OpenAI-compatible API',
    defaults: { name: 'QFOXAI' },
    inputs: [NodeConnectionType.Main],
    outputs: [NodeConnectionType.Main],
    credentials: [{ name: 'qfoxAiApi', required: true }],
    properties: [
      { displayName: 'Model', name: 'model', type: 'string', default: 'QFOXAI' },
      { displayName: 'Prompt', name: 'prompt', type: 'string', default: 'Summarize this item: {{$json.text}}', typeOptions: { rows: 4 } },
      { displayName: 'Max Tokens', name: 'maxTokens', type: 'number', default: 300 },
    ],
  };

  async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
    const items = this.getInputData();
    const credentials = await this.getCredentials('qfoxAiApi');
    const returnData: INodeExecutionData[] = [];

    for (let i = 0; i < items.length; i++) {
      const model = this.getNodeParameter('model', i) as string;
      const prompt = this.getNodeParameter('prompt', i) as string;
      const maxTokens = this.getNodeParameter('maxTokens', i) as number;

      const response = await this.helpers.httpRequest({
        method: 'POST',
        url: 'https://qfoxai.com/v1/chat/completions',
        headers: {
          Authorization: `Bearer ${credentials.apiKey}`,
          'Content-Type': 'application/json',
        },
        body: {
          model,
          messages: [{ role: 'user', content: prompt }],
          max_tokens: maxTokens,
        },
        json: true,
      });

      returnData.push({ json: { answer: response.choices?.[0]?.message?.content, response } });
    }

    return [returnData];
  }
}