const express = require('express');
const cors = require('cors');
require('dotenv').config();

const authRoutes = require('./routes/auth');
const academicRoutes = require('./routes/academic');
const profileRoutes = require('./routes/profile');
const subscriptionRoutes = require('./routes/subscription');
const paymentRoutes = require('./routes/payment');
const paymentWebhookRoutes = require('./routes/payment_webhook');
const locationRoutes = require('./routes/location');
const schoolRoutes = require('./routes/school');
const superadminRoutes = require('./routes/superadmin');
const parentRoutes = require('./routes/parent');
const moduleSubscriptionRoutes = require('./routes/moduleSubscription');
const adminRoutes = require('./routes/admin');
const settingsRoutes = require('./routes/settings');
const notificationRoutes = require('./routes/notification');

const app = express();
const PORT = process.env.PORT || 3002;

// CORS Middleware - Must be first
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Access-Control-Allow-Credentials', 'true');
  
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});

app.use(express.json());

// Routes
app.use('/api/auth', authRoutes);
app.use('/api/academic', academicRoutes);
app.use('/api/profile', profileRoutes);
app.use('/api/subscription', subscriptionRoutes);
app.use('/api/payment', paymentRoutes);
app.use('/api/payment', paymentWebhookRoutes);
app.use('/api/location', locationRoutes);
app.use('/api/school', schoolRoutes);
app.use('/api/superadmin', superadminRoutes);
app.use('/api/parent', parentRoutes);
app.use('/api/features', moduleSubscriptionRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/settings', settingsRoutes);
app.use('/api/notification', notificationRoutes);

// Health check
app.get('/api/health', (req, res) => {
  res.json({ message: 'Server is running' });
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});