const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '../../.env') });
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');

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

// Import routes and middleware
const authRoutes = require('./routes/auth');
const { 
  securityHeaders, 
  authErrorHandler 
} = require('./middleware/auth');

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

// ========================================
// MIDDLEWARE SETUP
// ========================================

// Security middleware
app.use(helmet({
  crossOriginEmbedderPolicy: false, // Allow embedding for dashboard
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'"],
      scriptSrc: ["'self'"],
      imgSrc: ["'self'", "data:", "https:"],
    },
  },
}));

app.use(securityHeaders);

// CORS configuration
const corsOptions = {
  origin: "*",
  credentials: true, // Allow cookies
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Session-Token', 'X-Platform', 'X-App-Version']
};

app.use(cors(corsOptions));

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

// Logging middleware
app.use(morgan('combined', {
  format: ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"'
}));

// Rate limiting disabled by request

// ========================================
// ROUTES
// ========================================

// Health check endpoint
app.get('/health', (req, res) => {
  res.status(200).json({
    status: 'healthy',
    service: 'user-auth',
    version: '1.0.0',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    features: {
      jwt_authentication: true,
      user_registration: true,
      feature_preferences: true,
      project_tracking: true,
      admin_panel: true,
      rate_limiting: true,
      session_management: true
    },
    database: {
      connected: true,
      type: 'PostgreSQL'
    },
    environment: process.env.NODE_ENV || 'development'
  });
});

// Root endpoint - API documentation
app.get('/', (req, res) => {
  res.json({
    message: 'User Authentication Service - JWT-based auth with feature preferences',
    version: '1.0.0',
    documentation: {
      base_url: `http://localhost:${PORT}`,
      endpoints: {
        health: '/health',
        auth: '/api/auth',
        register: 'POST /api/auth/register',
        login: 'POST /api/auth/login',
        logout: 'POST /api/auth/logout',
        refresh: 'POST /api/auth/refresh',
        profile: 'GET /api/auth/me',
        preferences: 'GET /api/auth/preferences/:templateType',
        projects: 'GET /api/auth/projects',
        admin_stats: 'GET /api/auth/admin/stats (Admin only)'
      },
      authentication: {
        type: 'JWT Bearer Token',
        header: 'Authorization: Bearer <token>',
        refresh: 'Use refresh token to get new access token'
      }
    },
    features: [
      'User registration and authentication',
      'JWT access and refresh tokens',
      'User feature preferences per template',
      'Project tracking and history',
      'Session management',
      'Rate limiting and security',
      'Admin statistics and cleanup'
    ]
  });
});

// Authentication routes
app.use('/api/auth', authRoutes);

// ========================================
// ERROR HANDLING
// ========================================

// 404 handler
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    error: 'Not Found',
    message: `Route ${req.originalUrl} not found`,
    available_routes: [
      'GET /health',
      'GET /',
      'POST /api/auth/register',
      'POST /api/auth/login',
      'GET /api/auth/me',
      'GET /api/auth/preferences/:templateType'
    ]
  });
});

// Global error handler
app.use(authErrorHandler);

// ========================================
// STARTUP AND CLEANUP
// ========================================

// Graceful shutdown handler
const gracefulShutdown = async (signal) => {
  console.log(`🛑 ${signal} received. Starting graceful shutdown...`);
  
  try {
    // Close database connections
    await database.close();
    console.log('📍 Database connections closed');
    
    console.log('✅ Graceful shutdown completed');
    process.exit(0);
  } catch (error) {
    console.error('❌ Error during shutdown:', error);
    process.exit(1);
  }
};

// Handle shutdown signals
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
  console.error('💥 Uncaught Exception:', error);
  gracefulShutdown('UNCAUGHT_EXCEPTION');
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('💥 Unhandled Rejection at:', promise, 'reason:', reason);
  gracefulShutdown('UNHANDLED_REJECTION');
});

// ========================================
// START SERVER
// ========================================

// Background cleanup task (runs every hour)
// Controlled by AUTH_CLEANUP_ENABLED env. Set to 'false' to disable automatic DB cleanup.
const startBackgroundTasks = () => {
  const enabled = (process.env.AUTH_CLEANUP_ENABLED || 'true').toLowerCase() !== 'false';
  if (!enabled) {
    console.log('⏸️  Background auth cleanup is disabled (AUTH_CLEANUP_ENABLED=false)');
    return;
  }
  setInterval(async () => {
    try {
      console.log('🧹 Running background auth cleanup...');
      const result = await authService.cleanup();
      console.log(`🧹 Cleanup completed: ${result.deletedTokens} tokens, ${result.inactiveSessions} sessions`);
    } catch (error) {
      console.error('❌ Background cleanup failed:', error);
    }
  }, 60 * 60 * 1000); // Every hour
};

// Start the server
app.listen(PORT, '0.0.0.0', () => {
  console.log('🚀 User Authentication 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(`📚 API docs: http://0.0.0.0:${PORT}/`);
  console.log('🔐 JWT-based authentication ready!');
  console.log('👥 User registration and feature preferences enabled');
  
  // Start background tasks (may be disabled by env)
  startBackgroundTasks();
  console.log('⏰ Background cleanup tasks scheduled');
  
  // Log environment info
  console.log(`🌍 Environment: ${process.env.NODE_ENV || 'development'}`);
  console.log(`🗄️ Database: PostgreSQL (${process.env.POSTGRES_HOST || 'localhost'})`);
  console.log('✨ Ready to authenticate users!');
});

module.exports = app;