// DbManager.ts
import { MongoClient, type Db } from 'mongodb';

export class DbManager {
  private mongoUri: string;
  private client: MongoClient;
  private db: Db | null;
  private connectPromise: Promise<Db> | null;

  constructor(mongoUri: string) {
    this.mongoUri = mongoUri;
    this.client = new MongoClient(mongoUri);
    this.db = null;
    this.connectPromise = null;
  }

  getDb = async (): Promise<Db> => {
    if (this.db) return this.db;

    if (!this.connectPromise) {
      this.connectPromise = this.client.connect().then(() => {
        this.db = this.client.db(); // DB from URI path
        return this.db;
      });
    }

    return this.connectPromise;
  };

  close = async (): Promise<void> => {
    await this.client.close().catch(() => {});
    this.db = null;
    this.connectPromise = null;
  };
}
