'use strict';

const client = require('better-call/client');

async function runHookWithShim(hookFn, createError, defaultMessage, errorStatus = 403) {
  let result;
  try {
    result = await hookFn();
  } catch (e) {
    throw createError(errorStatus, {
      message: e instanceof Error ? e.message : defaultMessage
    });
  }
  if (typeof result === "boolean") {
    if (process.env.NODE_ENV !== "production") {
      console.warn(
        `[btst] A lifecycle hook returned a boolean (${result}). Boolean returns are deprecated \u2014 throw an Error to deny access instead. IMPORTANT: any code path in this hook that falls through to undefined now ALLOWS access (previously denied). Update the hook to throw new Error("Unauthorized") to deny.`
      );
    }
    if (!result) {
      throw createError(errorStatus, { message: defaultMessage });
    }
  }
  return result;
}
async function runClientHookWithShim(hookFn, defaultMessage) {
  let result;
  try {
    result = await hookFn();
  } catch (e) {
    throw e instanceof Error ? e : new Error(defaultMessage);
  }
  if (typeof result === "boolean") {
    if (process.env.NODE_ENV !== "production") {
      console.warn(
        `[btst] A lifecycle hook returned a boolean (${result}). Boolean returns are deprecated \u2014 throw an Error to deny access instead. IMPORTANT: any code path in this hook that falls through to undefined now ALLOWS access (previously denied). Update the hook to throw new Error("Unauthorized") to deny.`
      );
    }
    if (!result) {
      throw new Error(defaultMessage);
    }
  }
  return result;
}
function isConnectionError(err) {
  if (!(err instanceof Error)) return false;
  const code = err.cause?.code ?? err.code;
  return err.message.includes("ECONNREFUSED") || err.message.includes("fetch failed") || err.message.includes("ERR_CONNECTION_REFUSED") || code === "ECONNREFUSED" || code === "ERR_CONNECTION_REFUSED";
}
function createApiClient(options) {
  const { baseURL = "", basePath = "/" } = options ?? {};
  const normalizedBaseURL = baseURL ? baseURL.replace(/\/$/, "") : "";
  const normalizedBasePath = basePath.startsWith("/") ? basePath : `/${basePath}`;
  const finalBasePath = normalizedBasePath.replace(/\/$/, "");
  const apiPath = normalizedBaseURL + finalBasePath;
  return client.createClient({
    baseURL: apiPath
  });
}

exports.createApiClient = createApiClient;
exports.isConnectionError = isConnectionError;
exports.runClientHookWithShim = runClientHookWithShim;
exports.runHookWithShim = runHookWithShim;
