import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import authRoutes from './routes/auth';
import monitorRoutes from './routes/monitors';
import settingsRoutes from './routes/settings';
import { authMiddleware } from './middleware/auth';
import { apiLimiter, authLimiter } from './middleware/rateLimiter';
import { startWorker, shutdownScheduler, getSchedulerStats } from './services/scheduler';

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

// Middleware
app.use(cors({
  origin: [process.env.APP_URL || 'http://localhost:3000', 'http://localhost:3020', 'http://localhost:3021'],
  credentials: true,
}));

app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// Apply general rate limiter to all API routes
app.use('/api/', apiLimiter);

// Request logging
app.use((req, _res, next) => {
  console.log(`${new Date().toISOString()} ${req.method} ${req.path}`);
  next();
});

// Health check
app.get('/health', async (_req, res) => {
  const schedulerStats = await getSchedulerStats();
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    scheduler: schedulerStats,
  });
});

import testRoutes from './routes/test';
import waitlistRoutes from './routes/waitlist';

// Routes
app.use('/api/auth', authLimiter, authRoutes);
app.use('/api/monitors', authMiddleware, monitorRoutes);
app.use('/api/settings', authMiddleware, settingsRoutes);
app.use('/api/waitlist', waitlistRoutes); // Public route - no auth required
app.use('/test', testRoutes);

// 404 handler
app.use((req, res) => {
  res.status(404).json({
    error: 'not_found',
    message: 'Endpoint not found',
    path: req.path,
  });
});

// Error handler
app.use((err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
  console.error('Unhandled error:', err);

  res.status(500).json({
    error: 'server_error',
    message: 'An unexpected error occurred',
  });
});

// Start Bull queue worker
const worker = startWorker();
console.log('📋 Bull queue worker initialized');

// Start server
app.listen(PORT, () => {
  console.log(`🚀 Server running on port ${PORT}`);
  console.log(`📊 Environment: ${process.env.NODE_ENV || 'development'}`);
  console.log(`🔗 API URL: http://localhost:${PORT}`);
});

// Graceful shutdown
process.on('SIGTERM', async () => {
  console.log('SIGTERM received, shutting down gracefully...');
  await worker.close();
  await shutdownScheduler();
  process.exit(0);
});

process.on('SIGINT', async () => {
  console.log('SIGINT received, shutting down gracefully...');
  await worker.close();
  await shutdownScheduler();
  process.exit(0);
});
