/**
 * Resolve a `db` config (from wrnexus.config.ts) to a live SQL `Db`. Kept in a
 * subpath (`@wrnexus/db/connect`) so importing the core `@wrnexus/db` doesn't pull
 * in every adapter. MongoDB is not here — it uses a document API (`@wrnexus/db/mongo`).
 */

import { isAbsolute, join } from "node:path";
import { createDb, type Db } from "./index.ts";
import { sqlite } from "./adapters/sqlite.ts";
import { postgres } from "./adapters/postgres.ts";
import { mysql } from "./adapters/mysql.ts";

export interface DbConfig {
  driver: string;
  url: string;
}

/** Resolve a `file:`/`sqlite:` URL's relative path against the app root. */
export function resolveDbUrl(url: string, appRoot?: string): string {
  const m = /^(?:file:|sqlite:\/\/|sqlite:)(.*)$/.exec(url);
  if (!m || !appRoot) return url;
  const path = m[1]!.replace(/^\.\//, "");
  return `file:${isAbsolute(path) ? path : join(appRoot, path)}`;
}

/** Build the configured SQL database (resolving a file URL against `appRoot`). */
export function connectFromConfig(config: DbConfig, appRoot?: string): Db {
  const url = resolveDbUrl(config.url, appRoot);
  switch (config.driver) {
    case "sqlite":
      return createDb(sqlite(url));
    case "postgres":
      return createDb(postgres(url));
    case "mysql":
      return createDb(mysql(url));
    default:
      throw new Error(
        `Database driver '${config.driver}' is not a SQL driver ` +
          `(use sqlite | postgres | mysql; MongoDB has a document API in @wrnexus/db/mongo).`,
      );
  }
}
