import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { initializeDatabase } from './config/database.js';
import authRoutes from './routes/auth.js';
import exchangeRoutes from './routes/exchange.js';

// Load environment variables
dotenv.config();

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

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

// Request logging middleware
app.use((req, res, next) => {
  if (process.env.NODE_ENV !== 'production') {
    console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  }
  next();
});

// Routes
app.use('/api/auth', authRoutes);
app.use('/api/exchange', exchangeRoutes);

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

// Root endpoint
app.get('/', (req, res) => {
  res.json({ 
    success: true,
    message: 'Nexora Exchange API',
    version: '1.0.0',
    endpoints: {
      health: '/api/health',
      auth: {
        login: 'POST /api/auth/login',
        changePassword: 'POST /api/auth/change-password',
        verify: 'GET /api/auth/verify',
        me: 'GET /api/auth/me'
      },
      exchange: {
        submitRequest: 'POST /api/exchange/request',
        getRates: 'GET /api/exchange/rates',
        getRequests: 'GET /api/exchange/requests (admin)',
        updateRequest: 'PATCH /api/exchange/requests/:id (admin)',
        updateRates: 'PUT /api/exchange/rates/:currencyPair (admin)'
      }
    }
  });
});

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

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

// Initialize database and start server
async function startServer() {
  try {
    await initializeDatabase();
    
    if (process.env.NODE_ENV !== 'production') {
      console.log('Database initialized successfully');
    }

    app.listen(PORT, () => {
      if (process.env.NODE_ENV === 'production') {
        console.log(`
╔════════════════════════════════════════════╗
║   ZAR-Naira Exchange API Server            ║
╚════════════════════════════════════════════╝
  
  Server Status: Running
  Environment: Production
  Port: ${PORT}
        `);
      } else {
        console.log(`
╔════════════════════════════════════════════╗
║   ZAR-Naira Exchange API Server            ║
╚════════════════════════════════════════════╝
  
  Server running on: http://localhost:${PORT}
  Environment: ${process.env.NODE_ENV || 'development'}
  
  API Documentation: http://localhost:${PORT}
  
  Press Ctrl+C to stop the server
        `);
      }
    });
  } catch (error) {
    console.error('Failed to start server:', error.message);
    process.exit(1);
  }
}

startServer();

export default app;
