import mongoose, { Connection } from 'mongoose';
import { env } from './env';

const MONGODB_URI = env.MONGODB_URI;

interface GlobalMongoDB {
  mongoose: {
    conn: Connection | null;
    promise: Promise<Connection> | null;
  };
}

declare global {
  var mongodb: GlobalMongoDB | undefined;
}

let cached = global.mongodb;

if (!cached) {
  cached = global.mongodb = { mongoose: { conn: null, promise: null } };
}

async function connectMongoDB(): Promise<Connection> {
  if (cached!.mongoose.conn) {
    return cached!.mongoose.conn;
  }

  if (!cached!.mongoose.promise) {
    const opts = {
      bufferCommands: false,
      maxPoolSize: 10,
      serverSelectionTimeoutMS: 5000,
      socketTimeoutMS: 45000,
    };

    cached!.mongoose.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
      console.log('✅ MongoDB connected successfully');
      return mongoose.connection;
    }).catch((error) => {
      console.error('❌ MongoDB connection error:', error);
      throw error;
    });
  }

  try {
    cached!.mongoose.conn = await cached!.mongoose.promise;
    return cached!.mongoose.conn;
  } catch (error) {
    cached!.mongoose.promise = null;
    throw error;
  }
}

export default connectMongoDB;
