import { IExecuteFunctions } from 'n8n-core';
import { INodeType, INodeTypeDescription, INodeExecutionData, NodeOperationError } from 'n8n-workflow';

const BASE_URL: Record<string, string> = {
  production: 'https://api.asaas.com',
  sandbox: 'https://api-sandbox.asaas.com',
};

export class Asaas implements INodeType {
  description: INodeTypeDescription = require('./Asaas.node.json');

  async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
    const creds = await this.getCredentials('asaasApi');
    const token = creds?.accessToken as string;
    const env = creds?.environment as 'production' | 'sandbox';
    const base = BASE_URL[env] + '';

    const items = this.getInputData();
    const results: INodeExecutionData[] = [];

    for (let i = 0; i < items.length; i++) {
      const method = this.getNodeParameter('method', i) as string;
      const endpoint = this.getNodeParameter('endpoint', i) as string;
      const payload = this.getNodeParameter('payload', i, {}) as Record<string, any>;

      let path = endpoint;
      Object.entries(payload).forEach(([k, v]) => {
        path = path.replace(new RegExp(`{${k}}`, 'g'), encodeURIComponent(String(v)));
      });

      const opts: Record<string, any> = {
        method,
        url: base + path,
        headers: { 'access_token': token, 'Content-Type': 'application/json' },
        json: true,
      };

      if (method === 'GET') {
        opts.qs = payload;
      } else {
        opts.body = payload;
      }

      try {
        const response = await this.helpers.request(opts);
        results.push({ json: response });
      } catch (err) {
        throw new NodeOperationError(this.getNode(), err as Error);
      }
    }
    return this.prepareOutputData(results);
  }
}