import { defaultOptions } from "./checks.js";
import { createHttpClient, getEnv } from "./http.js";

export function defineHttpSuite(configOrRun, maybeRun) {
  const { config, run } = normalizeSuiteArgs(configOrRun, maybeRun);
  const env = config.env || getEnv();
  const auth = config.auth || null;

  const client = createHttpClient({
    baseUrl: env.BASE,
    routeHeaders: env.routeParams,
    getHeaders(setupData) {
      return {
        ...callHeaders(auth?.headers, setupData, env),
        ...callHeaders(config.headers, setupData, env),
      };
    },
    getRawHeaders(setupData) {
      return callHeaders(config.rawHeaders, setupData, env);
    },
  });

  return {
    options: config.options || defaultOptions,
    setup() {
      if (typeof auth?.setup !== "function") return null;
      return auth.setup({ env });
    },
    exec(setupData) {
      return run({
        env,
        req: client.request,
        rawReq: client.raw,
        getWithHeaders: client.getWithHeaders,
        setupData,
        session: setupData,
      });
    },
  };
}

function normalizeSuiteArgs(configOrRun, maybeRun) {
  if (typeof configOrRun === "function") {
    return { config: {}, run: configOrRun };
  }
  if (typeof maybeRun !== "function") {
    throw new Error("suite factory requires a run callback");
  }
  return { config: configOrRun || {}, run: maybeRun };
}

function callHeaders(builder, setupData, env) {
  if (typeof builder !== "function") return {};
  return builder(setupData, { env }) || {};
}
