import type {
  IExecuteFunctions,
  ILoadOptionsFunctions,
  IHttpRequestOptions,
  INodeListSearchItems,
} from 'n8n-workflow';

import { dataProductOptions, normalizeBaseUrl } from './contracts';

type NdcHttpContext = IExecuteFunctions | ILoadOptionsFunctions;

export function serviceBaseUrl(environmentVariable: string, defaultBaseUrl: string): string {
  return normalizeBaseUrl(process.env[environmentVariable] || defaultBaseUrl);
}

export async function ndcRequest(
  context: NdcHttpContext,
  credentialName: string,
  options: IHttpRequestOptions,
): Promise<unknown> {
  return context.helpers.httpRequestWithAuthentication.call(context, credentialName, {
    ...options,
    json: true,
  });
}

export async function loadDataProductOptions(
  context: ILoadOptionsFunctions,
  credentialName: string,
  baseUrlEnvironmentVariable: string,
  defaultBaseUrl: string,
  catalogPath: string,
): Promise<INodeListSearchItems[]> {
  const baseUrl = serviceBaseUrl(baseUrlEnvironmentVariable, defaultBaseUrl);
  const response = await ndcRequest(context, credentialName, {
    method: 'GET',
    url: `${baseUrl}${catalogPath}`,
  });
  return dataProductOptions(response);
}
