// lib/db.js
import mongoose from "mongoose";

// Reuse the connection across hot reloads in dev and across route handler invocations.
const globalForMongoose = globalThis;

const cached =
	globalForMongoose.__mongooseCache ||
	(globalForMongoose.__mongooseCache = { conn: null, promise: null });

async function connectMongoose() {
	const uri = process.env.MONGODB_URI;

	if (!uri) {
		throw new Error("MONGODB_URI environment variable is not set");
	}

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

	if (!cached.promise) {
		cached.promise = mongoose
			.connect(uri, {
				// Fail fast if someone queries before we are connected
				bufferCommands: false,
			})
			.then((m) => m);
	}

	cached.conn = await cached.promise;
	return cached.conn;
}

/**
 * Returns the native MongoDB db handle (from the active Mongoose connection).
 * This also ensures the Mongoose connection is established.
 */
export async function getDb() {
	await connectMongoose();

	const db = mongoose.connection?.db;
	if (!db) {
		throw new Error("MongoDB connection is not ready");
	}

	return db;
}
