import pgPromise from "pg-promise";
import * as pgMonitor from "pg-monitor";
import { dbInitOptions, IRepositories, AppDatabase } from "@digiresilience/metamigo-db";
import config from "@digiresilience/metamigo-config";
import type { IInitOptions } from "pg-promise";

export const initDiagnostics = (
  logSql: boolean,
  initOpts: IInitOptions<IRepositories>
): void => {
  if (logSql) {
    pgMonitor.attach(initOpts);
  } else {
    pgMonitor.attach(initOpts, ["error"]);
  }
};

export const stopDiagnostics = (): void => pgMonitor.detach();

let pgp: any;
let pgpInitOptions: any;

export const initPgp = (): void => {
  pgpInitOptions = dbInitOptions(config);
  pgp = pgPromise(pgpInitOptions);
};

const initDb = (): AppDatabase => {
  const db = pgp(config.db.connection);
  return db;
};

export const stopDb = async (db: AppDatabase): Promise<void> => {
  return db.$pool.end();
};

export const withDb = <T>(f: (db: AppDatabase) => Promise<T>): Promise<T> => {
  const db = initDb();
  initDiagnostics(config.logging.sql, pgpInitOptions);
  try {
    return f(db);
  } finally {
    stopDiagnostics();
  }
};

export type { AppDatabase } from "@digiresilience/metamigo-db";
