const express = require('express');
const dotenv = require('dotenv');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('../docs/swaggerSpec.js');
const morgan = require('morgan');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const healthCheck = require('./utils/health.js');

dotenv.config();

healthCheck();

// Rate limiting middleware
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per windowMs
  message: 'Too many requests, please try again later.',
});

exports.paymentLimiter = rateLimit({
  windowMs: 60 * 60 * 1000, // 1 hour
  max: 5,
  message: 'Too many payment requests, please try again later.',
});

const app = express();
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
app.use(morgan('dev'));
app.use(cors());
app.use(limiter);

// Swagger documentation
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use('/docs.json', (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  res.send(swaggerDocument);
});

// Mount user routes
app.use('/api/auth', require('./routes/auth'));
app.use('/api/products', require('./routes/product'));
app.use('/api/orders', require('./routes/order'));
app.use('/api/transactions', require('./routes/transaction'));
app.use('/api/bid', require('./routes/bid'));
app.use('/api/users', require('./routes/user'));
app.use('/api/admin', require('./routes/admin'));
app.use('/api/wallet', require('./routes/wallet'));
app.use('/api/conversations', require('./routes/conversation'));

const notificationRoutes = require('./routes/notification');
const referralRoutes = require('./routes/referral');
const activityLogRoutes = require('./routes/activityLog');

app.use('/api/notifications', notificationRoutes);
app.use('/api/referrals', referralRoutes);
app.use('/api/activity-logs', activityLogRoutes);


// Catch-all route for undefined endpoints
app.use((req, res) => {
  res.status(404).json({ error: 'Not Found' });
});

module.exports = app;
