import { Collection, Db, MongoClient, type Document } from "mongodb";
import dbConfig from "../config/database";

class DatabaseService {
  private client: MongoClient;
  private db: Db | null = null;
  private static instance: DatabaseService;

  private constructor() {
    this.client = new MongoClient(dbConfig.uri);
  }

  static getInstance(): DatabaseService {
    if (!DatabaseService.instance) {
      DatabaseService.instance = new DatabaseService();
    }
    return DatabaseService.instance;
  }

  async connect(): Promise<void> {
    try {
      await this.client.connect();
      this.db = this.client.db(dbConfig.dbName);
      console.log("Connected to MongoDB successfully");
    } catch (error) {
      console.error("Failed to connect to MongoDB", error);
      throw error;
    }
  }

  getCollection<T extends Document>(collectionName: string): Collection<T> {
    if (!this.db) {
      throw new Error(
        "Database connection not established. Call connect() first.",
      );
    }
    return this.db.collection<T>(collectionName);
  }

  async disconnect(): Promise<void> {
    if (this.client) {
      await this.client.close();
      console.log("Disconnected from MongoDB");
    }
  }
}

export default DatabaseService;
