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

const { sequelize, testConnection } = require('./config/database');
const authRoutes = require('./routes/auth');
const chitGroupRoutes = require('./routes/chitGroups');
const memberRoutes = require('./routes/members');
const paymentRoutes = require('./routes/payments');
const monthlyDrawRoutes = require('./routes/monthlyDraws');
const shareRoutes = require('./routes/share');
const notificationRoutes = require('./routes/notifications');
const ReminderService = require('./services/reminder-service');

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

// Security middleware - temporarily disabled for debugging
// app.use(helmet());

// CORS configuration - Allow all origins for development
app.use(cors({
  origin: '*',
  credentials: false,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'Accept']
}));

// Rate limiting - temporarily disabled for debugging
// const limiter = rateLimit({
//   windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000, // 15 minutes
//   max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100, // limit each IP to 100 requests per windowMs
//   message: 'Too many requests from this IP, please try again later.'
// });
// app.use('/api', limiter);

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

// Logging middleware
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({
    success: true,
    message: 'LuckyChit API is running',
    timestamp: new Date().toISOString(),
    environment: process.env.NODE_ENV
  });
});

// API routes
app.use('/api/auth', authRoutes);
app.use('/api/chit-groups', chitGroupRoutes);
app.use('/api/members', memberRoutes);
app.use('/api/payments', paymentRoutes);
app.use('/api/monthly-draws', monthlyDrawRoutes);
app.use('/api/share', shareRoutes);
app.use('/api/notifications', notificationRoutes);

// 404 handler - removed for now to fix path-to-regexp issue
// app.use('/*', (req, res) => {
//   res.status(404).json({
//     success: false,
//     message: 'Route not found'
//   });
// });

// Global error handler
app.use((err, req, res, next) => {
  console.error('Global error handler:', err);
  
  res.status(err.status || 500).json({
    success: false,
    message: err.message || 'Internal server error',
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
  });
});

// Start server
const startServer = async () => {
  try {
    // Test database connection
    console.log('🔌 Attempting to connect to database...');
    await testConnection();
    
    // Sync database models
    console.log('🔄 Syncing database models...');
    await sequelize.sync({ alter: true });
    console.log('✅ Database models synchronized');
    
    // Start payment reminder scheduler
    console.log('⏰ Starting payment reminder scheduler...');
    ReminderService.startScheduler();
    
    // Start server
    app.listen(PORT, () => {
      console.log(`🚀 Server running on port ${PORT}`);
      console.log(`📊 Environment: ${process.env.NODE_ENV}`);
      console.log(`🔗 Health check: http://localhost:${PORT}/health`);
      console.log(`🔗 API base: http://localhost:${PORT}/api`);
      console.log(`📱 WhatsApp share: http://localhost:${PORT}/api/share`);
      console.log(`🔔 Notifications: http://localhost:${PORT}/api/notifications`);
    });
  } catch (error) {
    console.error('❌ Database connection failed:', error.message);
    console.log('💡 Please ensure PostgreSQL is running and the database credentials are correct.');
    console.log('💡 You can also try:');
    console.log('   1. Check if PostgreSQL service is running');
    console.log('   2. Verify database credentials in .env file');
    console.log('   3. Create the database: CREATE DATABASE luckychit;');
    process.exit(1);
  }
};

startServer();
