/**
 * ============================================
 * AERIX GLOBAL - TASK MANAGEMENT SYSTEM
 * Main Server Entry Point
 * ============================================
 */

const express = require("express");
const cors = require("cors");
const helmet = require("helmet");
const morgan = require("morgan");
const dotenv = require("dotenv");

// Load environment variables
dotenv.config();

// Import custom modules
const routes = require("./routes");
const { errorHandler, notFound } = require("./middleware/errorMiddleware");
const { connectDatabase } = require("./config/database");

// Initialize Express app
const app = express();

// Security middleware
app.use(helmet());

// CORS configuration
app.use(
  cors({
    origin: process.env.FRONTEND_URL || "http://localhost:3000",
    credentials: true,
    methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
    allowedHeaders: ["Content-Type", "Authorization"],
  }),
);

// Request logging
app.use(morgan("combined"));

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

// Health check endpoint
app.get("/health", (req, res) => {
  res.status(200).json({
    status: "healthy",
    timestamp: new Date().toISOString(),
    service: "Aerix Task Management API",
  });
});

// API Routes
app.use("/api", routes);

// Handle 404 errors
app.use(notFound);

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

// Database connection and server start
const PORT = process.env.PORT || 5000;

const startServer = async () => {
  try {
    // Test database connection
    await connectDatabase();
    console.log("✅ Database connected successfully");

    // Start server
    app.listen(PORT, () => {
      console.log(`
╔════════════════════════════════════════════════════════╗
║     AERIX GLOBAL - TASK MANAGEMENT SYSTEM              ║
║     Server running on port ${PORT}                         ║
║     Environment: ${process.env.NODE_ENV || "development"}                       ║
╚════════════════════════════════════════════════════════╝
            `);
    });
  } catch (error) {
    console.error("❌ Failed to start server:", error.message);
    process.exit(1);
  }
};

startServer();
