import express from "express";
import cors from "cors";
import path from "node:path";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import dotenv from "dotenv";

import crawlRoutes from "./routes/crawl.routes.js";
import sitemapRoutes from "./routes/sitemap.routes.js";
import authRoutes from "./routes/auth.routes.js"; // Login & Signup endpoints
import paymentRoutes from "./routes/payment.route.js";
import lighthouseRoutes from "./routes/lighthouse.routes.js"; // <-- ADD THIS
import messageRoutes from "./routes/message.routes.js";
import cakeOrderRoutes from "./routes/maisondetreats/cakeOrder.routes.js";
import blogRoutes from "./routes/blog.routes.js";
import { connectDB } from "./config/db.js";
import { mailer } from "./utils/mailer.js";

// ------------------ Load environment ------------------
dotenv.config(); // Must be first

// ------------------ Connect database ------------------
await connectDB();

// ------------------ Express setup ------------------
const app = express();
const PORT = process.env.PORT || 3010;
const __dirname = path.dirname(fileURLToPath(import.meta.url));

app.use(express.json());
app.use(
  cors({
    origin: [
      "http://localhost:3000",
      "http://127.0.0.1:3000",
      "https://api.crawlerx.co",
      "https://app.crawlerx.co",
      "https://maisondetreats.com/"
    ],
  })
);
app.use(express.static(path.join(__dirname, "public")));

// ------------------ SMTP verification ------------------

console.log("SMTP Host:", process.env.SMTP_HOST);
console.log("SMTP Port:", process.env.SMTP_PORT);
// ------------------ Routes ------------------
app.get("/", (_req, res) => {
  const viewer = path.join(__dirname, "public", "crawlerx_viewer.html");
  if (fs.existsSync(viewer)) {
    return res.sendFile(viewer);
  } else {
    return res
      .type("text/plain")
      .send("CrawlerX backend is running.");
  }
});

app.get("/healthz", (_req, res) => res.json({ ok: true, time: new Date().toISOString() }));

app.use("/crawl", crawlRoutes);
app.use("/sitemap", sitemapRoutes);
app.use("/api/auth", authRoutes); // Login & Signup endpoints
app.use("/api/payment", paymentRoutes);
app.use("/api/lighthouse", lighthouseRoutes);
app.use("/api/blog", blogRoutes); // All blog/category/comment routes now prefixed with /api/blog
app.use("/api/messages", messageRoutes);
app.use("/api/cake-orders", cakeOrderRoutes);

// Serve uploaded files
app.use('/uploads', express.static(path.join(process.cwd(), 'uploads')));

// ------------------ Safety nets ------------------
process.on("unhandledRejection", (err) => console.error("Unhandled Rejection:", err));
process.on("uncaughtException", (err) => console.error("Uncaught Exception:", err));

// ------------------ Start server ------------------
app.listen(PORT, "0.0.0.0", () => {
  console.log(`🚀 Server running at http://localhost:${PORT}`);
});
