import mongoose from 'mongoose';
import { GridFSBucket } from 'mongodb';

export let bucket: GridFSBucket;

export const connectDB = async () => {
    try {
        const uri = process.env.MONGODB_URI;
        if (!uri) {
            throw new Error('MONGODB_URI is not defined in environment variables');
        }

        if (mongoose.connection.readyState >= 1) {
            console.log('Using existing MongoDB connection');
            if (!bucket && mongoose.connection.db) {
                bucket = new GridFSBucket(mongoose.connection.db, { bucketName: 'pdfs' });
                console.log('✅ GridFS Bucket re-initialized');
            }
            return;
        }

        console.log('Connecting to MongoDB...');
        if (!uri) console.error('MONGODB_URI is undefined!');

        await mongoose.connect(uri, {
            maxPoolSize: 10,
            serverSelectionTimeoutMS: 5000,
            socketTimeoutMS: 45000,
        });
        console.log('✅ MongoDB connected successfully');

        const db = mongoose.connection.db;
        if (!db) {
            throw new Error('Database connection not established');
        }
        bucket = new GridFSBucket(db, {
            bucketName: 'pdfs'
        });
        console.log('✅ GridFS Bucket initialized');

    } catch (error) {
        console.error('❌ MongoDB connection error:', error);
        console.warn('⚠️ Server will continue running for debugging, but database features will be unavailable.');
        // process.exit(1);
    }
};
