import express from "express";
import { createServer } from "http";
import path from "path";
import { fileURLToPath } from "url";
import fs from "fs";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function startServer() {
  const app = express();
  const server = createServer(app);

  app.use(express.json());

  // API endpoint to submit lead to user-provided CRM webhook
  app.post("/api/submit-lead", async (req, res) => {
    try {
      const leadData = req.body;
      const webhookUrl = process.env.CRM_WEBHOOK_URL || leadData.webhookUrl;

      if (!leadData.address || !leadData.name || !leadData.phone) {
        return res.status(400).json({ success: false, error: "Missing required fields (address, name, phone)." });
      }

      // If a webhook URL is configured (either env or request), forward the lead
      if (webhookUrl) {
        try {
          const response = await fetch(webhookUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              source: "Home Buyers Nationwide",
              timestamp: new Date().toISOString(),
              ...leadData,
            }),
          });
          if (!response.ok) {
            console.error(`Webhook forward failed with status ${response.status}`);
          }
        } catch (err) {
          console.error("Error forwarding lead to webhook:", err);
        }
      }

      // Log lead to local server console/file for reliability
      const logEntry = `[${new Date().toISOString()}] LEAD: ${JSON.stringify(leadData)}\n`;
      fs.appendFileSync(path.resolve(__dirname, "..", "leads.log"), logEntry);

      return res.json({ success: true, message: "Lead successfully captured and routed." });
    } catch (error) {
      console.error("Lead submission error:", error);
      return res.status(500).json({ success: false, error: "Internal server error." });
    }
  });

  // XML Sitemap generator route
  app.get("/sitemap.xml", (req, res) => {
    try {
      const baseUrl = `${req.protocol}://${req.get("host") || "localhost:3000"}`;
      
      let sitemap = `<?xml version="1.0" encoding="UTF-8"?>\n`;
      sitemap += `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n`;

      // Core static routes
      const staticRoutes = [
        "",
        "/sell-your-house-fast.html",
        "/how-it-works.html",
        "/situations.html",
        "/locations.html",
        "/about.html",
        "/contact.html",
        "/privacy.html",
        "/terms.html"
      ];

      for (const route of staticRoutes) {
        sitemap += `  <url>\n`;
        sitemap += `    <loc>${baseUrl}${route}</loc>\n`;
        sitemap += `    <changefreq>weekly</changefreq>\n`;
        sitemap += `    <priority>${route === "" ? "1.0" : "0.8"}</priority>\n`;
        sitemap += `  </url>\n`;
      }

      // Read states and counties from shared data if available
      try {
        const statesDataPath = path.resolve(__dirname, "..", "client", "src", "data", "states.ts");
        // We can include state directory routes
        const states = ["alabama", "arizona", "arkansas", "california", "colorado", "connecticut", "delaware", "florida", "georgia", "idaho", "illinois", "indiana", "iowa", "kansas", "kentucky", "louisiana", "maine", "maryland", "massachusetts", "michigan", "minnesota", "mississippi", "missouri", "montana", "nebraska", "nevada", "new-hampshire", "new-jersey", "new-mexico", "new-york", "north-carolina", "north-dakota", "ohio", "oklahoma", "oregon", "pennsylvania", "rhode-island", "south-carolina", "south-dakota", "tennessee", "texas", "utah", "vermont", "virginia", "washington", "west-virginia", "wisconsin", "wyoming"];
        
        for (const st of states) {
          sitemap += `  <url>\n`;
          sitemap += `    <loc>${baseUrl}/locations/${st}.html</loc>\n`;
          sitemap += `    <changefreq>monthly</changefreq>\n`;
          sitemap += `    <priority>0.7</priority>\n`;
          sitemap += `  </url>\n`;
        }
      } catch (e) {
        console.error("Error generating location sitemap entries:", e);
      }

      sitemap += `</urlset>`;

      res.header("Content-Type", "application/xml");
      return res.send(sitemap);
    } catch (error) {
      console.error("Sitemap generation error:", error);
      return res.status(500).send("Error generating sitemap");
    }
  });

  // Serve static files from dist/public in production
  const staticPath =
    process.env.NODE_ENV === "production"
      ? path.resolve(__dirname, "public")
      : path.resolve(__dirname, "..", "dist", "public");

  app.use(express.static(staticPath));

  // Handle client-side routing - serve index.html for all routes
  app.get("*", (_req, res) => {
    res.sendFile(path.join(staticPath, "index.html"));
  });

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

  server.listen(port, () => {
    console.log(`Server running on http://localhost:${port}/`);
  });
}

startServer().catch(console.error);
