import type { VercelRequest, VercelResponse } from '@vercel/node';
import mongoose from 'mongoose';

export default async function handler(req: VercelRequest, res: VercelResponse) {
    try {
        const uri = process.env.MONGODB_URI;
        if (!uri) throw new Error('MONGODB_URI is missing from Vercel settings');

        await mongoose.connect(uri);
        const state = mongoose.connection.readyState;
        await mongoose.disconnect();

        res.json({
            success: true,
            message: 'MongoDB Connection verified!',
            state: state === 1 ? 'Connected' : state
        });
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        const stack = error instanceof Error ? error.stack : undefined;
        res.status(500).json({
            success: false,
            error: message,
            stack: stack
        });
    }
}
