import express, { type Request, Response, NextFunction } from "express";
import session from "express-session";
import MemoryStore from "memorystore";
import { registerRoutes } from './routes.js';
import path from "path";
import { registerTemplateRoutes } from './template-routes.js';
import { storage } from './storage.js';

const app = express();

// Session configuration with MemoryStore
const MemStore = MemoryStore(session);
app.use(session({
  secret: process.env.SESSION_SECRET || 'locallendables_secret_key_2024',
  store: new MemStore({
    checkPeriod: 86400000 // prune expired entries every 24h
  }),
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: false, // Disable secure for Replit environment
    httpOnly: true,
    maxAge: 24 * 60 * 60 * 1000 // 24 hours
  }
}));

// Basic middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// CORS for all routes
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  next();
});

// Serve static files with aggressive cache-busting
const publicPath = path.resolve(import.meta.dirname, "..", "public");
app.use(express.static(publicPath, {
  setHeaders: (res, path) => {
    const cacheVersion = Date.now();
    res.set({
      'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0',
      'Pragma': 'no-cache', 
      'Expires': '0',
      'ETag': `"${cacheVersion}"`,
      'Last-Modified': new Date().toUTCString()
    });
  }
}));

// Global cache-busting middleware for all HTML responses
app.use((req: Request, res: Response, next: NextFunction) => {
  // Aggressive cache-busting for all HTML responses
  const cacheVersion = Date.now();
  res.set({
    'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0, private',
    'Pragma': 'no-cache',
    'Expires': '0',
    'Last-Modified': new Date().toUTCString(),
    'ETag': `"v${cacheVersion}"`,
    'Vary': 'Cache-Control'
  });
  
  // Log forwarded requests but allow them (Replit needs these headers)
  if (req.headers['x-forwarded-proto'] || req.headers['x-forwarded-host']) {
    console.log('Forwarded request from Replit webview:', req.url);
  }
  
  next();
});

// Request logging
app.use((req, res, next) => {
  const start = Date.now();
  const path = req.path;
  let capturedJsonResponse: Record<string, any> | undefined = undefined;

  const originalResJson = res.json;
  res.json = function (bodyJson, ...args) {
    capturedJsonResponse = bodyJson;
    return originalResJson.apply(res, [bodyJson, ...args]);
  };

  res.on("finish", () => {
    const duration = Date.now() - start;
    if (path.startsWith("/api")) {
      let logLine = `${req.method} ${path} ${res.statusCode} in ${duration}ms`;
      if (capturedJsonResponse) {
        logLine += ` :: ${JSON.stringify(capturedJsonResponse)}`;
      }
      console.log(logLine);
    }
  });

  next();
});

// Error handling middleware
app.use((err: any, _req: Request, res: Response, _next: NextFunction) => {
  const status = err.status || err.statusCode || 500;
  const message = err.message || "Internal Server Error";
  console.error('Server error:', err);
  res.status(status).send(message);
});

// Register routes
registerTemplateRoutes(app, storage);
registerRoutes(app);

// Start server
const port = parseInt(process.env.PORT || '5000');
const host = '0.0.0.0';

const server = app.listen(port, host, () => {
  console.log(`LocalLendables STABLE Express SSR server running on ${host}:${port}`);
  console.log(`Access at: http://localhost:${port}`);
  console.log(`Demo users available - click any avatar on homepage`);
  console.log(`STABLE MODE: No auto-restart on file changes`);
}).on('error', (err) => {
  console.error('Server failed to start:', err);
  process.exit(1);
});

// Prevent auto-restart by handling signals
process.on('SIGTERM', () => {
  console.log('SIGTERM received, keeping server running...');
});

process.on('SIGINT', () => {
  console.log('SIGINT received, keeping server running...');
});