import type { OptionsWithUri } from 'request';

import type {
	IDataObject,
	IExecuteFunctions,
	IExecuteSingleFunctions,
	IHookFunctions,
	ILoadOptionsFunctions,
	IOAuth2Options,
	JsonObject,
} from 'n8n-workflow';
import { NodeApiError } from 'n8n-workflow';
import { BASE_API_URL } from './GenericConstants';

type N8nThis = IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions | IHookFunctions;

export async function rdStationApiRequest(
	this: N8nThis,
	method: string,
	resource: string,

	body: IDataObject = {},
	qs: IDataObject = {},
	uri?: string,
	optionOverrides: IDataObject = {},
): Promise<any> {
	const endpoint = (uri ?? `${BASE_API_URL}/platform${resource}`) as string;

	let options: OptionsWithUri = {
		method,
		uri: endpoint,
		qs,
		headers: {
			'Content-Type': 'application/json',
			'Accept': 'application/json',
		},
		json: true,
		...optionOverrides,
	};

	if (Object.keys(body).length > 0) {
		options.body = body;
	}

	const oAuth2Options: IOAuth2Options = {
		tokenType: 'Bearer',
		includeCredentialsOnRefreshOnBody: true,
	};

	try {
		// @ts-ignore: helpers context is not well typed
		return await this.helpers.requestOAuth2.call(this, 'rdsmEcommerceOAuth2Api', options, oAuth2Options);
	} catch (error) {
		throw new NodeApiError(this.getNode(), error as JsonObject);
	}
}
