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

export default async function handler(req: VercelRequest, res: VercelResponse) {
    try {
        console.log('--- API CALL:', req.url);

        // Inline connection to avoid external file dependency issues during boot
        if (mongoose.connection.readyState !== 1) {
            const uri = process.env.MONGODB_URI;
            if (!uri) throw new Error('MONGODB_URI environment variable is missing');
            await mongoose.connect(uri);
        }

        // Use the localized app.js
        return app(req, res);
    } catch (error: unknown) {
        console.error('SERVERLESS BOOT ERROR:', error);
        const message = error instanceof Error ? error.message : 'Unknown error';
        return res.status(500).json({
            error: 'Serverless Boot Error',
            message: message,
            path: req.url,
            suggestion: 'Check Vercel Logs for module resolution errors'
        });
    }
}
