import express, { type Express } from "express";
import fs from "fs";
import path from "path";
import { log } from "./vite";

/**
 * Production-safe static file serving that doesn't throw errors
 * This replaces the problematic serveStatic function in production
 */
export function serveProductionStatic(app: Express): boolean {
  // Check multiple possible build directories
  const possiblePaths = [
    path.resolve("dist", "public"),     // Standard build output
    path.resolve("client", "dist"),     // Alternative build location
    path.resolve("build"),              // Another common build directory
    path.resolve("public")              // Direct public folder
  ];

  let distPath: string | null = null;
  
  // Find the first existing directory
  for (const possiblePath of possiblePaths) {
    if (fs.existsSync(possiblePath)) {
      distPath = possiblePath;
      break;
    }
  }

  if (!distPath) {
    log("No build directory found. Available options checked: " + possiblePaths.join(", "));
    return false;
  }

  log(`Serving static files from: ${distPath}`);

  // Serve static files
  app.use(express.static(distPath));

  // Fallback to index.html for SPA routing
  app.use("*", (_req, res) => {
    const indexPath = path.resolve(distPath!, "index.html");
    
    if (fs.existsSync(indexPath)) {
      res.sendFile(indexPath);
    } else {
      // Graceful fallback if index.html doesn't exist
      res.status(404).json({ 
        error: "Application not found", 
        message: "The application's index file is missing from the build directory." 
      });
    }
  });

  return true;
}

/**
 * Emergency fallback server for when no static files are available
 */
export function serveFallbackApp(app: Express): void {
  app.use("*", (_req, res) => {
    res.status(503).json({ 
      error: "Service temporarily unavailable", 
      message: "The application is not properly built. Please run 'npm run build' and try again.",
      timestamp: new Date().toISOString()
    });
  });
}