require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
const apiRoutes = require('./routes/api');

const app = express();
const PORT = process.env.PORT || 5000;
const MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost:27017/school-portal';

// Middlewares
app.use(cors());
// Increased body parsing limits to support base64 image uploads directly to database
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));

// API Routes
app.use('/api', apiRoutes);

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

// Database Connection & Server Startup
const { MongoMemoryServer } = require('mongodb-memory-server');

let mongoServer;

const connectDB = async () => {
  try {
    console.log(`Connecting to MongoDB at ${MONGO_URI}...`);
    // Connect with a 2-second timeout so it doesn't hang if Mongo is not running
    await mongoose.connect(MONGO_URI, { serverSelectionTimeoutMS: 2000 });
    console.log('Connected to local MongoDB successfully!');
  } catch (err) {
    console.warn('Failed to connect to local MongoDB. Initializing In-Memory MongoDB database...');
    try {
      mongoServer = await MongoMemoryServer.create();
      const inMemoryUri = mongoServer.getUri();
      console.log(`In-Memory MongoDB started at: ${inMemoryUri}`);
      await mongoose.connect(inMemoryUri);
      console.log('Connected to In-Memory MongoDB successfully!');
    } catch (memErr) {
      console.error('Failed to start In-Memory MongoDB:', memErr.message);
      process.exit(1);
    }
  }
};

connectDB().then(() => {
  app.listen(PORT, () => {
    console.log(`Backend server is running on http://localhost:${PORT}`);
  });
});
