require('dotenv').config();
var express = require('express');
var mongoose = require('mongoose');
var cors = require('cors');
var protect = require('./middleware/authMiddleware');

var authRoutes = require('./routes/authRoutes');
var customerRoutes = require('./routes/customerRoutes');
var productRoutes = require('./routes/productRoutes');
var saleRoutes = require('./routes/saleRoutes');
var reportRoutes = require('./routes/reportRoutes');

var app = express();

app.use(cors({
  origin: 'http://localhost:5173',
  credentials: true
}));
app.use(express.json());

app.use('/api/auth', authRoutes);
app.use('/api/customers', protect, customerRoutes);
app.use('/api/products', protect, productRoutes);
app.use('/api/sales', protect, saleRoutes);
app.use('/api/reports', protect, reportRoutes);

app.get('/', function(req, res) {
  res.json({ message: 'SRMS API running' });
});

var PORT = process.env.PORT || 5000;
var MONGO_URI = process.env.MONGO_URI;

if (!MONGO_URI) {
  console.error('MONGO_URI is missing in .env');
  process.exit(1);
}

mongoose.connect(MONGO_URI)
  .then(function() {
    console.log('MongoDB connected');
    app.listen(PORT, function() {
      console.log('Server running on port ' + PORT);
    });
  })
  .catch(function(error) {
    console.error('MongoDB connection error:', error.message);
    process.exit(1);
  });
