import mongoose from 'mongoose';

const MONGODB_URI = process.env.MONGODB_URI;

// We do NOT throw an error here anymore to allow the app to build/run 
// in "Demo Mode" without a .env file.

interface MongooseCache {
  conn: typeof mongoose | null;
  promise: Promise<typeof mongoose> | null;
}

let cached = (globalThis as any).mongoose;

if (!cached) {
  cached = (globalThis as any).mongoose = { conn: null, promise: null };
}

async function dbConnect() {
  // If no URI is provided, we return null so the app handles it gracefully (Demo Mode)
  if (!MONGODB_URI) {
    console.warn("WARN: No MONGODB_URI found in .env. App running in Demo/Mock mode.");
    return null;
  }

  if (cached.conn) {
    return cached.conn;
  }

  if (!cached.promise) {
    const opts = {
      bufferCommands: false,
    };

    cached.promise = mongoose.connect(MONGODB_URI!, opts).then((mongoose) => {
      return mongoose;
    });
  }

  try {
    cached.conn = await cached.promise;
  } catch (e) {
    cached.promise = null;
    throw e;
  }

  return cached.conn;
}

export default dbConnect;