import "./set-env.js"
// Import this first for Sentry to be initialized before other imports!
import "./instrument.js"

import express from "express"
import cors from "cors"
import { addAsync } from "@awaitjs/express"

import { AsyncExpressApp } from "./types.js"
import { logger } from "./utils/logger.js"
import { posthog } from "./analytics.js"
import { GlobalExceptionHandler } from "./exceptions/index.js"
import { githubApp } from "./github/github-app.js"
import { enhancedRequestLogger } from "./middlewares/enhanced-logging.js"
import { registerRoutes } from "./routes/index.js"
import { initializeCronJobs } from "./cron/index.js"
import { DEFAULT_PORT, GITHUB_WEBHOOK_PATH } from "./constants/index.js"

// ========================================
// APPLICATION SETUP
// ========================================

const port = process.env.PORT ?? DEFAULT_PORT
const appExpress = addAsync(express()) as any as AsyncExpressApp

// ========================================
// CRON JOBS
// ========================================

initializeCronJobs(githubApp)

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

// Enhanced logging (must be first)
appExpress.use(enhancedRequestLogger)

// CORS handling
if (process.env.NODE_ENV !== "PRODUCTION") {
  logger.info("CORS: Allowing all origins in development", {
    operation: "server_startup",
  })
  appExpress.use(cors({ origin: "*" }))
}

// Log GitHub webhook middleware mounting
logger.info("Mounting GitHub webhook middleware", {
  operation: "server_startup",
  path: GITHUB_WEBHOOK_PATH,
})

// ========================================
// ROUTE REGISTRATION
// ========================================

// Register all routes (body parser is inside registerRoutes, after webhook routes)
registerRoutes(appExpress)

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

appExpress.use(GlobalExceptionHandler.handle)

// ========================================
// SERVER STARTUP
// ========================================

appExpress.listen(Number(port), () => {
  logger.info("CF API server started successfully", {
    operation: "server_startup",
    port: Number(port),
    environment: process.env.NODE_ENV,
    githubWebhookPath: GITHUB_WEBHOOK_PATH,
  })
})

posthog?.shutdown()

// Handle unhandled promise rejections and uncaught exceptions
process.on("unhandledRejection", GlobalExceptionHandler.handleUnhandledRejection)
process.on("uncaughtException", GlobalExceptionHandler.handleUncaughtException)
