import { MongoClient, Db } from 'mongodb';

let client: MongoClient | undefined;
let db: Db | undefined;

export class MongoClientService {
	private static _url: string | undefined;
	private static _databaseName: string | undefined;

	static configure(url: string, databaseName: string): void {
		this._url = url;
		this._databaseName = databaseName;
	}

	static getUrl(): string {
		if (!this._url) {
			const url = process.env.MONGODB_AUDIT_URL;
			if (!url) {
				throw new Error('Missing MONGODB_AUDIT_URL environment variable');
			}
			this._url = url;
		}
		return this._url;
	}

	static getDatabaseName(): string {
		if (!this._databaseName) {
			this._databaseName = process.env.MONGODB_AUDIT_DATABASE ?? 'sso_audit';
		}
		return this._databaseName;
	}

	static async getClient(): Promise<MongoClient> {
		if (!client) {
			client = new MongoClient(this.getUrl());
			await client.connect();
		}
		return client;
	}

	static async getDb(): Promise<Db> {
		if (!db) {
			const c = await this.getClient();
			db = c.db(this.getDatabaseName());
		}
		return db;
	}

	static async close(): Promise<void> {
		if (client) {
			await client.close();
			client = undefined;
			db = undefined;
		}
	}
}
