import { FastifyPluginAsync } from 'fastify';
import fp from 'fastify-plugin';
import axios, { AxiosRequestConfig, Method, AxiosError } from 'axios';
import { HttpMethod } from '../../../plugins/shared/types';

interface ApiRequestOptions {
    baseURL: string;
}

interface ApiKey {
    apikey: string;
}

const apiRequestPlugin: FastifyPluginAsync<ApiRequestOptions> = async (fastify, options) => {
    const { baseURL } = options;

    fastify.decorate(
        'makeApiRequest',
        async (method: HttpMethod, url: string, apiKey: ApiKey, body?: Record<string, unknown>) => {
            const config: AxiosRequestConfig = {
                method: method as Method,
                url: baseURL + url,
                data: body,
                headers: { Authorization: `Bearer ${apiKey.apikey}` },
            };

            try {
                const response = await axios(config);
                return response.data;
            } catch (err: unknown) {
                const axiosError = err as AxiosError;
                if (axiosError.response) {
                    return {
                        error: true,
                        statusCode: axiosError.response.status,
                        message: axiosError.response.data,
                    };
                } else if (axiosError.request) {
                    return {
                        error: true,
                        statusCode: 504,
                        message: 'No response from server',
                    };
                } else {
                    return {
                        error: true,
                        statusCode: 500,
                        message: axiosError.message || 'Server error',
                    };
                }
            }
        }
    );
};

export default fp(apiRequestPlugin);
