import { MongoClient, Db } from "mongodb"; import { setDb } from "./index"; import { validateConfig, validateMongoUri } from "../utils/validation"; class WebsitalkMongoDBClient { private client: MongoClient | null = null; private db: Db | null = null; private readonly defaultDbName = "website-talk"; async connect(uri?: string, dbName?: string): Promise { if (this.client) { return; } const mongodbUri = uri || process.env.MONGO_URI || process.env.MONGODB_URI; validateConfig("MONGO_URI", mongodbUri); validateMongoUri(mongodbUri!); try { this.client = new MongoClient(mongodbUri!); await this.client.connect(); const targetDbName = dbName || process.env.WEBSITALK_DB_NAME || this.defaultDbName; this.db = this.client.db(targetDbName); setDb(this.db); console.info(`[core-db] Website Talk MongoDB connected: ${targetDbName}`); } catch (error) { console.error("[core-db] Website Talk connection failed", error); throw error; } } async disconnect(): Promise { if (this.client) { try { await this.client.close(); this.client = null; this.db = null; console.info("Website Talk MongoDB disconnected successfully"); } catch (error) { console.error("[core-db] Website Talk disconnection failed", error); throw error; } } } getDb(): Db { if (!this.db) { throw new Error( "Website Talk database not initialized. Call connect() first.", ); } return this.db; } isConnected(): boolean { return this.client !== null && this.client !== undefined; } } export const websitalkMongodbClient = new WebsitalkMongoDBClient();