/**
 * SCMS Backend Server
 * - Express.js API server
 * - Loads environment variables
 * - Sets up middleware (CORS, JSON)
 * - Mounts API routes
 */

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

const { errorHandler } = require('./middleware/errorHandler');

const authRoutes = require('./routes/auth.routes');
const supplierRoutes = require('./routes/supplier.routes');
const shipmentRoutes = require('./routes/shipment.routes');
const deliveryRoutes = require('./routes/delivery.routes');
const reportRoutes = require('./routes/report.routes');

const { notFoundHandler } = require('./middleware/notFound');

const app = express();

app.use(cors());
app.use(express.json({ limit: '1mb' }));

// Health check
app.get('/health', (_req, res) => {
  return res.json({ ok: true });
});

// Routes
app.use('/api/auth', authRoutes);

// Protected business APIs
app.use('/api/suppliers', supplierRoutes);
app.use('/api/shipments', shipmentRoutes);
app.use('/api/deliveries', deliveryRoutes);

// Reports (protected)
app.use('/api/reports', reportRoutes);

// 404 + error handling
app.use(notFoundHandler);
app.use(errorHandler);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  // eslint-disable-next-line no-console
  console.log(`SCMS backend running on port ${PORT}`);
});

