import express, { Express, Request, Response, NextFunction } from 'express';
import http from 'http';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import dotenv from 'dotenv';
import apiRoutes from './routes/index.js';
import authRoutes from './routes/auth.routes.js';
import propertyRoutes from './routes/properties.routes.js';
import messageRoutes from './routes/messages.routes.js';
import adminRoutes from './routes/admin.routes.js';
import catalogRoutes from './routes/catalog.routes.js';
import adminCatalogRoutes from './routes/admin.catalog.routes.js';
import { initSocket } from './lib/socket.js';
import { startAutoArchiveJob } from './jobs/autoArchive.js';
import { startBrokerDetectionJob } from './jobs/brokerDetection.js';
import { startFeaturedExpiryJob } from './jobs/featuredExpiry.js';
import settingsRoutes from './routes/settings.routes.js';
import agentsRoutes from './routes/agents.routes.js';
import agentRoutes from './routes/agent.routes.js';
import boostRoutes from './routes/boost.routes.js';
import propertyDraftRoutes from './routes/propertyDrafts.routes.js';
import developerRoutes from './routes/developer.routes.js';
import { startAgentSubscriptionExpiryJob } from './jobs/agentSubscriptionExpiry.js';
import { UPLOAD_ROOT } from './config/uploads.js';
import mobileRoutes from './routes/mobile.routes.js';
import { initializeFirebase } from './lib/fcm.js';

dotenv.config();

// Initialize Firebase Admin SDK for FCM notifications
initializeFirebase();

const app: Express = express();

// We are running behind Apache as a reverse proxy, which sets X-Forwarded-*
// headers. Tell Express to trust the first proxy so that middleware like
// express-rate-limit can accurately determine the client IP.
app.set('trust proxy', 1);

// Frontend origins allowed to call the API / load resources
// Use environment variables for all origins, with localhost fallbacks for development.
// These are used both for HTTP CORS checks and for Socket.io.
const FRONTEND_ORIGINS = [
  process.env.CORS_ORIGIN || 'http://localhost:8080',
  process.env.FRONTEND_URL || 'http://localhost:8080',
  process.env.ADMIN_URL || 'http://localhost:8081',
  // Production domains (HTTPS)
  'https://property.cool.et',
  'https://propertyadmin.cool.et',
  // Local development origins
  'http://localhost:3000',
  'http://localhost:5173',
  'http://localhost:8080',
  'http://localhost:8081',
  'http://127.0.0.1:3000',
  'http://127.0.0.1:5173',
  'http://127.0.0.1:8080',
  'http://127.0.0.1:8081',
  // Additional origins from env (comma-separated)
  ...(process.env.CORS_ADDITIONAL_ORIGINS
    ? process.env.CORS_ADDITIONAL_ORIGINS.split(',').map((o) => o.trim()).filter(Boolean)
    : []),
].filter(Boolean);

const isAllowedOrigin = (origin?: string | null) => {
  if (!origin) return false;
  return FRONTEND_ORIGINS.includes(origin);
};

// Security middleware with CSP and relaxed image/embed settings
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        // Allow styles from self and inline (for now); can be tightened later if needed.
        styleSrc: ["'self'", "'unsafe-inline'"],
        // Disallow inline scripts to strengthen XSS protection.
        scriptSrc: ["'self'"],
        // Allow images from any origin over HTTP/HTTPS, plus data/blob URLs.
        imgSrc: ["'self'", 'data:', 'blob:', 'http:', 'https:'],
      },
    },
    // Allow resources (like images) to be loaded from other origins (e.g., Vite dev server)
    crossOriginResourcePolicy: { policy: 'cross-origin' },
    // Avoid strict COEP for this app to keep things simple
    crossOriginEmbedderPolicy: false,
  }),
);

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

// NOTE: Rate limiting via express-rate-limit has been temporarily disabled
// because of issues with X-Forwarded-For validation behind Apache. We can
// reintroduce it later with a custom configuration once everything else
// is stable.

// CORS configuration for API routes
// Only allow known frontend origins; reject others.
app.use(
  '/api',
  cors({
    origin: (origin, callback) => {
      if (!origin || isAllowedOrigin(origin)) {
        return callback(null, true);
      }
      return callback(new Error('CORS origin not allowed'), false);
    },
    credentials: true,
    optionsSuccessStatus: 200,
  }),
);

// Static uploads with simple CORS (mainly for XHR/fetch; CORP is handled by helmet above)
app.use(
  '/uploads',
  cors({
    origin: (origin, callback) => {
      if (!origin || isAllowedOrigin(origin)) {
        return callback(null, true);
      }
      return callback(new Error('CORS origin not allowed'), false);
    },
    credentials: false,
    optionsSuccessStatus: 200,
  }),
  // Serve files from the configured uploads root (can be on /Data)
  express.static(UPLOAD_ROOT),
);

// Runtime config inspection endpoint (useful for debugging env / CORS / URLs)
app.get('/config', (req: Request, res: Response) => {
  const port = PORT;
  const apiBaseUrl = process.env.API_BASE_URL || `http://localhost:${port}/api`;

  res.json({
    status: 'ok',
    env: process.env.NODE_ENV || 'development',
    port,
    apiBaseUrl,
    corsOrigin: process.env.CORS_ORIGIN || null,
    frontendOrigins: FRONTEND_ORIGINS,
    ip: req.ip,
    hostname: req.hostname,
  });
});

// Health check route
app.get('/health', (req: Request, res: Response) => {
  res.json({
    status: 'ok',
    message: 'Cool Property Finder API is running',
    timestamp: new Date().toISOString(),
  });
});

// API routes
app.use('/api', apiRoutes);
app.use('/api/auth', authRoutes);
app.use('/api/catalog', catalogRoutes);
app.use('/api/properties', propertyRoutes);
app.use('/api/property-drafts', propertyDraftRoutes);
app.use('/api/agents', agentsRoutes);
app.use('/api/agent', agentRoutes);
app.use('/api/developer', developerRoutes);
app.use('/api/boost', boostRoutes);
  app.use('/api', mobileRoutes);
app.use('/api', messageRoutes);
app.use('/api', settingsRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/admin/catalog', adminCatalogRoutes);

// 404 handler
app.use((req: Request, res: Response) => {
  res.status(404).json({
    error: 'Not Found',
    message: `Route ${req.originalUrl} not found`,
  });
});

// Error handler
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  console.error('Error:', err);
  res.status(err.status || 500).json({
    error: err.message || 'Internal Server Error',
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
  });
});

const PORT = process.env.PORT || 3000;

export const startServer = () => {
  const server = http.createServer(app);

  // Configure HTTP server timeouts to avoid hanging/CLOSE_WAIT connections
  // and keep them compatible with reverse proxies (Apache).
  // keepAliveTimeout should be less than or equal to the proxy's timeout.
  server.keepAliveTimeout = 65000; // 65 seconds
  server.headersTimeout = 70000;   // slightly higher than keepAliveTimeout

  const io = initSocket(server, FRONTEND_ORIGINS);

  server.listen(PORT, () => {
    console.log(`🚀 Server is running on http://localhost:${PORT}`);
    console.log(`📊 Environment: ${process.env.NODE_ENV || 'development'}`);
    if (io) {
      console.log('🔌 Socket.io initialized for real-time messaging');
    }
  });

  // Start background jobs
  startAutoArchiveJob();
  startBrokerDetectionJob();
  startFeaturedExpiryJob();
  startAgentSubscriptionExpiryJob();

  return { server, io };
};

export default app;
