import axios, { AxiosRequestConfig, Method, AxiosResponse, AxiosError } from 'axios';
import UnableToProceed from '../../../../shared/exceptions/UnableToProceed';
import Unauthorized from '../../../../shared/exceptions/Unauthorized';
import { HttpMethod } from '../../../../plugins/shared/types';
import { ChatGptRequestConfig } from '../../types/chatgpt';

class ChatGptRequest {
    private static readonly baseURL: string = 'https://api.openai.com/v1';
    private static readonly apiKey: string = process.env.CHATGPT_API_KEY || '';

    public static async doRequest<T>(
        method: HttpMethod,
        endpoint: string,
        body?: { model: string; messages: { role: string; content: string }[] },
        headersExtra?: Record<string, string>
    ): Promise<T> {
        const headers = {
            Authorization: `Bearer ${ChatGptRequest.apiKey}`,
            'Content-Type': 'application/json',
            ...headersExtra,
        };

        const requestBody = {
            model: 'gpt-4', // Default model
            ...body,
        };

        const config: AxiosRequestConfig = {
            method: method as Method,
            url: `${ChatGptRequest.baseURL}${endpoint}`,
            headers,
            data: requestBody,
        };

        console.log(`Sending request to OpenAI: ${config.url}`);
        console.log('Request Headers:', headers);
        console.log('Request Body:', JSON.stringify(requestBody, null, 2));

        try {
            const response: AxiosResponse<T> = await axios(config);
            console.log('Received response from OpenAI:', JSON.stringify(response.data, null, 2));
            return response.data;
        } catch (error: unknown) {
            const axiosError = error as AxiosError;
            console.error(`Error from OpenAI request to ${endpoint}:`, axiosError);
            if (axiosError.response) {
                console.error('Response Data:', JSON.stringify(axiosError.response.data, null, 2));
                if (axiosError.response.status === 401) {
                    throw new Unauthorized('Unauthorized access');
                }
                throw new UnableToProceed(
                    `HTTP ${axiosError.response.status} error at ${endpoint}: ${JSON.stringify(axiosError.response.data, null, 2)}`
                );
            } else if (axiosError.request) {
                console.error('No response received from OpenAI');
                throw new UnableToProceed('No response from server');
            } else {
                console.error('Unexpected error:', axiosError.message);
                throw new UnableToProceed(axiosError.message);
            }
        }
    }
}

export default ChatGptRequest; 