import express, { Application, Request, Response, NextFunction } from 'express';
import cors from 'cors';
import taskRoutes from './routes/task.routes';
import workflowRoutes from './routes/workflow.routes';
import assignmentRoutes from './routes/assignment.routes';
import notificationRoutes from '../notifications/notificationRoutes';
import collaborationRoutes from '../collaboration/collaborationRoutes';
import createNLPRoutes from './routes/nlp.routes';
import aiRoutes from './routes/ai.routes';
import { generalLimiter } from './middleware/rateLimit.middleware';

// Create Express application
const app: Application = express();

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Apply general rate limiting to all routes
app.use(generalLimiter);

// Health check endpoint
app.get('/health', (_req: Request, res: Response) => {
  res.json({
    success: true,
    message: 'API is running',
    timestamp: new Date().toISOString()
  });
});

// API Routes
app.use('/api/tasks', taskRoutes);
app.use('/api/workflow', workflowRoutes);
app.use('/api/assignments', assignmentRoutes);
app.use('/api/notifications', notificationRoutes);
app.use('/api/collaboration', collaborationRoutes);
app.use('/api/ai', aiRoutes);
app.use('/api/nlp', createNLPRoutes());

// 404 handler
app.use((_req: Request, res: Response) => {
  res.status(404).json({
    success: false,
    error: 'Route not found'
  });
});

// Global error handler
app.use((err: any, _req: Request, res: Response, _next: NextFunction) => {
  console.error('Error:', err);
  
  res.status(err.status || 500).json({
    success: false,
    error: err.message || 'Internal server error',
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
  });
});

export default app;