// index.js
if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}

const express     = require('express');
const cors        = require('cors');
const morgan      = require('morgan');
const helmet      = require('helmet');
const rateLimit   = require('express-rate-limit');

const connectDB    = require('./config/db');
const userRoutes   = require('./routes/userRoutes');
const ticketRoutes = require('./routes/ticketRoutes');

connectDB();

const app = express();

// Trust proxy (Heroku, Nginx, etc.)
app.set('trust proxy', 1);

// Security headers
app.use(helmet());

// Rate limiting
app.use(
  '/api/',
  rateLimit({
    windowMs: 15*60*1000,
    max: 100,
  })
);

// CORS config
const corsOptions = {
  origin: ['https://quantumens.com', 'https://www.quantumens.com', 'http://localhost:3000'],
  methods: ['GET','POST','PUT','DELETE','OPTIONS'],
  allowedHeaders: ['Content-Type','Authorization'],
  credentials: true
};

// Apply CORS to all routes
app.use(cors(corsOptions));

// Explicitly handle preflight
app.options('*', cors(corsOptions));

// Logging
app.use(
  process.env.NODE_ENV === 'production'
    ? morgan('combined')
    : morgan('dev')
);

// Body parser
app.use(express.json({ limit: '10kb' }));

// Routes
app.use('/api/users',   userRoutes);
app.use('/api/tickets', ticketRoutes);
app.get('/', (req, res) => res.send('API is running...'));

// 404 and error handlers
app.use((req, res) => res.status(404).json({ message: 'Not Found' }));
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: 'Server Error' });
});

// Start
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () =>
  console.log(`Server running on port ${PORT}`)
);

process.on('unhandledRejection', err => {
  console.error('Unhandled Rejection:', err);
  server.close(() => process.exit(1));
});