console.log('Loading Netlify Function...');
import serverless from 'serverless-http';
import express from 'express';
import cors from 'cors';

// Import local database connection that sets up GridFS/Bucket
import { connectDB } from '../../src/server/config/database.js';

// Static imports for routes to ensure esbuild bundles them correctly
import projectRoutes from '../../src/server/routes/projectRoutes.js';
import partRoutes from '../../src/server/routes/partRoutes.js';
import paintingSchemeRoutes from '../../src/server/routes/paintingSchemeRoutes.js';
import applicationRecordRoutes from '../../src/server/routes/applicationRecordRoutes.js';
import inspectionRoutes from '../../src/server/routes/inspectionRoutes.js';
import analysisRoutes from '../../src/server/routes/analysisRoutes.js';
import dataSheetRoutes from '../../src/server/routes/dataSheetRoutes.js';
import yieldStudyRoutes from '../../src/server/routes/yieldStudyRoutes.js';
import userRoutes from '../../src/server/routes/userRoutes.js';
import uploadsRoutes from '../../src/server/routes/uploadsRoutes.js';
import systemSettingsRoutes from '../../src/server/routes/systemSettingsRoutes.js';
import geometryTypeRoutes from '../../src/server/routes/geometryTypeRoutes.js';

const app = express();
app.use(cors({
    origin: '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'x-clerk-user-id', 'x-organization-id']
}));
app.use(express.json());

// Routes
// We register them immediately since we use serverless-http's cold start handling
app.use('/api/users', userRoutes);
app.use('/api/projects', projectRoutes);
app.use('/api/parts', partRoutes);
app.use('/api/painting-schemes', paintingSchemeRoutes);
app.use('/api/application-records', applicationRecordRoutes);
app.use('/api/inspections', inspectionRoutes);
app.use('/api', analysisRoutes);
app.use('/api/datasheets', dataSheetRoutes);
app.use('/api/yield-studies', yieldStudyRoutes);
app.use('/api/system-settings', systemSettingsRoutes);
app.use('/api/geometry-types', geometryTypeRoutes);

// Serve uploads (from /tmp in serverless or local dir)
app.use('/uploads', uploadsRoutes);

// Simple test endpoint
app.get('/api/health', (req, res) => {
    res.json({
        status: 'ok',
        timestamp: new Date()
    });
});

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const handler = async (event: any, context: any) => {
    context.callbackWaitsForEmptyEventLoop = false;

    // Ensure DB is connected before processing request
    try {
        await connectDB();
    } catch (e) {
        console.error('DB Connection Failed:', e);
        // We let it proceed, maybe it's a health check or will fail gracefully later
    }

    const httpHandler = serverless(app);
    return await httpHandler(event, context);
};
