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

// Import routes
const authRoutes = require('./server/routes/auth');
const bookingRoutes = require('./server/routes/bookings');
const vehicleRoutes = require('./server/routes/vehicles');
const pricingRoutes = require('./server/routes/pricing');
const quoteRoutes = require('./server/routes/quotes');
const adminRoutes = require('./server/routes/admin');
const paymentRoutes = require('./server/routes/payments');
const messageRoutes = require('./server/routes/messages');
const blockedDatesRoutes = require('./server/routes/blocked-dates');

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

// Security middleware
app.use(helmet({
    contentSecurityPolicy: false, // Allow inline scripts for development
}));

// Rate limiting
const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100 // limit each IP to 100 requests per windowMs
});
app.use('/api/', limiter);

// Stricter rate limit for auth endpoints
const authLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 50, // Increased for development/testing
    message: 'Too many login attempts, please try again later'
});
app.use('/api/auth/login', authLimiter);
app.use('/api/auth/register', authLimiter);

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

// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// API Routes
app.use('/api/auth', authRoutes);
app.use('/api/bookings', bookingRoutes);
app.use('/api/vehicles', vehicleRoutes);
app.use('/api/pricing', pricingRoutes);
app.use('/api/quotes', quoteRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/payments', paymentRoutes);
app.use('/api/messages', messageRoutes);
app.use('/api/blocked-dates', blockedDatesRoutes);

// Health check endpoint
app.get('/api/health', (req, res) => {
    res.json({
        status: 'healthy',
        timestamp: new Date().toISOString(),
        uptime: process.uptime(),
        environment: process.env.NODE_ENV || 'development'
    });
});

// Serve frontend pages (static files middleware handles this now)

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

// Initialize database and start server
async function startServer() {
    try {
        // Initialize database
        console.log('🔧 Initializing database...');
        await database.initialize();
        
        // Start server
        app.listen(PORT, '0.0.0.0', () => {
            console.log('╔══════════════════════════════════════════════════════╗');
            console.log('║   ASH TRANSFER - FULL-STACK BACKEND SERVER          ║');
            console.log('╚══════════════════════════════════════════════════════╝');
            console.log('');
            console.log(`✓ Server running on http://localhost:${PORT}`);
            console.log(`✓ Environment: ${process.env.NODE_ENV || 'development'}`);
            console.log(`✓ Database: SQLite (${database.db ? 'Connected' : 'Error'})`);
            console.log('');
            console.log('📋 API Endpoints:');
            console.log(`   • Auth:      http://localhost:${PORT}/api/auth`);
            console.log(`   • Bookings:  http://localhost:${PORT}/api/bookings`);
            console.log(`   • Vehicles:  http://localhost:${PORT}/api/vehicles`);
            console.log(`   • Pricing:   http://localhost:${PORT}/api/pricing`);
            console.log(`   • Quotes:    http://localhost:${PORT}/api/quotes`);
            console.log(`   • Admin:     http://localhost:${PORT}/api/admin`);
            console.log(`   • Payments:  http://localhost:${PORT}/api/payments`);
            console.log(`   • Messages:  http://localhost:${PORT}/api/messages`);
            console.log('');
            console.log('🔐 Admin Login:');
            console.log('   Email:    admin@ashtransfer.com');
            console.log('   Password: Global2026@');
            console.log('');
            console.log('Press Ctrl+C to stop the server');
            console.log('═══════════════════════════════════════════════════════');
        });
    } catch (error) {
        console.error('Failed to start server:', error);
        process.exit(1);
    }
}

// Handle shutdown gracefully
process.on('SIGTERM', async () => {
    console.log('SIGTERM received, closing server...');
    await database.close();
    process.exit(0);
});

process.on('SIGINT', async () => {
    console.log('\nSIGINT received, closing server...');
    await database.close();
    process.exit(0);
});

// Start the server
startServer();

module.exports = app;
