import { DB } from "sqlite";
import { createSchema } from "./user.ts";

let inmemoryDB: DB | undefined;
let previousPath = "";
let dbCache: DB | undefined;

export async function connectDB(): Promise<DB> {
  let DB_path = Deno.env.get("DB_PATH");
  if (DB_path === ":memory:") {
    if (inmemoryDB === undefined) {
      inmemoryDB = new DB(":memory:");
      await createSchema(inmemoryDB);
    }
    return inmemoryDB;
  } else if (DB_path === undefined) {
    Deno.env.set("DB_PATH", "db.sqlite");
    DB_path = "db.sqlite";
  }
  if (dbCache !== undefined && DB_path === previousPath) {
    return dbCache;
  } else {
    dbCache?.close();
    dbCache = undefined;
  }
  const db = new DB(DB_path);
  previousPath = DB_path;
  dbCache = db;
  await createSchema(db);
  return db;
}
