// Imports
import { migrate } from "postgres-migrations";
import createPgp from "pg-promise";
import moment from "moment";
import { WARN } from "../util/logging.js";
// Environment Variables
const {
  POSTGRES_DATABASE: database,
  POSTGRES_DISABLED: pgDisabled,
  POSTGRES_HOST: host,
  POSTGRES_PASSWORD: password,
  POSTGRES_PORT: port,
  POSTGRES_USER: user,
} = process.env;

// Postgres-promise Configuration
// Ensure dates get saved as UTC date strings
// This prevents the parser from doing strange datetime operations
const pgp = createPgp();
pgp.pg.types.setTypeParser(1114, (str) => moment.utc(str).format());

// Database Config
const dbConfig = {
  database: database ?? "qualiteer",
  user: user ?? "postgres",
  password: password ?? "postgres",
  host: host ?? "localhost",
  port: port ?? 5432,
  ensureDatabaseExists: true,
};

const migrationsDir = "lib/database/migrations";

const configure = async () => {
  if (pgDisabled) {
    WARN("POSTGRES", "Postgres Disabled!");
    return { query: (str) => INFO("POSTGRES MOCK", str) };
  }
  await migrate(dbConfig, migrationsDir);
  // Override the global variable DB
  const pg = pgp(dbConfig);
  await pg.connect();
  OK("POSTGRES", `Connected to database ${database}!`);
  return pg;
};

export default await configure();
