import { defaultOptions } from "./checks.js";
import { createDalContext, openDb } from "./dal.js";

export function defineDalSuite(configOrRun, maybeRun) {
  const { config, run } = normalizeSuiteArgs(configOrRun, maybeRun);
  const db = config.db || openDb();
  const dal = createDalContext(db);

  return {
    options: config.options || defaultOptions,
    setup() {
      if (typeof config.setup !== "function") return null;
      return config.setup({ db, dal });
    },
    exec(setupData) {
      return run({
        db,
        dal,
        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 };
}
