require('dotenv').config();
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const http = require('http');
const { Server } = require('socket.io');

// Import database
const database = require('./config/database');

// Import routes (we'll create these next)
const templateRoutes = require('./routes/templates');
const featureRoutes = require('./routes/features');
const learningRoutes = require('./routes/learning');
const adminRoutes = require('./routes/admin');
const AdminNotification = require('./models/admin_notification');
// const customTemplateRoutes = require('./routes/custom_templates');

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: process.env.FRONTEND_URL || "http://localhost:3000",
    methods: ["GET", "POST"],
    credentials: true
  }
});
const PORT = process.env.PORT || 8009;

// Middleware
app.use(helmet());
app.use(cors());
app.use(morgan('combined'));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// Make io available to routes and set it in AdminNotification
app.set('io', io);
AdminNotification.setSocketIO(io);

// Routes - Order matters! More specific routes should come first
app.use('/api/learning', learningRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/templates', templateRoutes);
// Add admin routes under /api/templates to match serviceClient expectations
app.use('/api/templates/admin', adminRoutes);
// Features route must come AFTER templates to avoid route conflicts
app.use('/api/features', featureRoutes);
// Single route surface: handle custom templates via /api/templates only
// app.use('/api/custom-templates', customTemplateRoutes);

// WebSocket connection handling
io.on('connection', async (socket) => {
  console.log('🔌 Admin client connected:', socket.id);
  
  // Join admin room for notifications
  socket.join('admin-notifications');
  
  // Send initial notification count
  try {
    const counts = await AdminNotification.getCounts();
    socket.emit('notification-count', counts);
  } catch (error) {
    console.error('Error getting notification counts:', error);
    socket.emit('notification-count', { total: 0, unread: 0, read: 0 });
  }
  
  socket.on('disconnect', () => {
    console.log('🔌 Admin client disconnected:', socket.id);
  });
});

// Health check endpoint
app.get('/health', (req, res) => {
  res.status(200).json({
    status: 'healthy',
    service: 'template-manager',
    version: '1.0.0',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    features: {
      template_management: true,
      feature_learning: true,
      usage_tracking: true,
      self_improving: true,
      admin_approval_workflow: true
    }
  });
});

// Root endpoint
app.get('/', (req, res) => {
  res.json({
    message: 'Template Manager Service - Self-Learning Feature Database',
    version: '1.0.0',
    endpoints: {
      health: '/health',
      templates: '/api/templates',
      features: '/api/features',
      learning: '/api/learning',
      admin: '/api/admin',
      customTemplates: '/api/custom-templates'
    }
  });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error('❌ Error:', err.stack);
  res.status(500).json({
    error: 'Internal Server Error',
    message: process.env.NODE_ENV === 'development' ? err.message : 'Something went wrong'
  });
});

// 404 handler
app.use('*', (req, res) => {
  res.status(404).json({
    error: 'Not Found',
    message: `Route ${req.originalUrl} not found`
  });
});

// Graceful shutdown
process.on('SIGINT', async () => {
  console.log('🛑 Shutting down Template Manager...');
  await database.close();
  process.exit(0);
});

// Start server
server.listen(PORT, '0.0.0.0', () => {
  console.log('🚀 Template Manager Service started');
  console.log(`📡 Server running on http://0.0.0.0:${PORT}`);
  console.log(`🏥 Health check: http://0.0.0.0:${PORT}/health`);
  console.log('🔌 WebSocket server ready for real-time notifications');
  console.log('🎯 Self-learning feature database ready!');
});

module.exports = app;