import axios, { AxiosRequestConfig } from 'axios';

export interface HttpRequestInput {
  url: string;
  method: string;
  headers?: Record<string, string>;
  body?: any;
  timeout?: number;
  authentication?: string;
  followRedirects?: boolean;
  responseFormat?: 'json' | 'text' | 'binary';
  ignoreSslErrors?: boolean;
}

export interface HttpRequestOutput {
  status: number;
  data: any;
  headers: Record<string, string>;
}

/**
 * Execute an HTTP request activity.
 */
export async function httpRequest(input: HttpRequestInput): Promise<HttpRequestOutput> {
  const axiosConfig: AxiosRequestConfig = {
    url: input.url,
    method: input.method.toLowerCase() as any,
    headers: input.headers || {},
    timeout: input.timeout || 30000,
    maxRedirects: input.followRedirects === false ? 0 : 5,
    validateStatus: () => true, // Don't throw on non-2xx
  };

  if (input.body && ['post', 'put', 'patch'].includes(axiosConfig.method as string)) {
    axiosConfig.data = input.body;
  }

  if (input.ignoreSslErrors) {
    const https = await import('https');
    axiosConfig.httpsAgent = new https.Agent({ rejectUnauthorized: false });
  }

  if (input.responseFormat === 'binary') {
    axiosConfig.responseType = 'arraybuffer';
  }

  const response = await axios(axiosConfig);

  return {
    status: response.status,
    data: response.data,
    headers: response.headers as Record<string, string>,
  };
}
