const express = require("express");
const path = require("path");
const cors = require("cors");
require("dotenv").config();
const cookieParser = require("cookie-parser");

// Rotaların import edilmesi
const userRoutesneedRefactor = require("./routes/user.routes");
const dealRoutes = require("./routes/deal.routes");
const authRoutes = require("./routes/auth.routes");
const dealVoteRoutes = require("./routes/vote.routes");
const commentRoutes = require("./routes/comment.routes");
const accountSettingsRoutes = require("./routes/accountSettings.routes");
const userRoutes = require("./routes/user.routes");
const sellerRoutes = require("./routes/seller.routes");
const voteRoutes = require("./routes/vote.routes");
const commentLikeRoutes = require("./routes/commentLike.routes");
const categoryRoutes =require("./routes/category.routes")
const modRoutes = require("./routes/mod.routes")
const uploadRoutes = require("./routes/upload.routes")
const badgeRoutes = require("./routes/badge.routes")
const cacheRoutes = require("./routes/cache.routes")
const { ensureDealSearchIndex } = require("./services/redis/searchIndex.service")
const { seedRecentDealsToRedis, seedReferenceDataToRedis } = require("./services/redis/dealIndexing.service")
const { ensureCommentIdCounter } = require("./services/redis/commentId.service")
const { ensureDealIdCounter } = require("./services/redis/dealId.service")
const dealDb = require("./db/deal.db")
const { slugify } = require("./utils/slugify")
const { requestContextMiddleware } = require("./services/requestContext")
const app = express();

app.set("trust proxy", true)

// CORS middleware'ı ile dışardan gelen istekleri kontrol et
const allowedOrigins = new Set([
  "http://192.168.1.205:3001",
  "http://localhost:3001",
  "http://localhost:3000",
]);

app.use(
  cors({
    origin(origin, cb) {
      if (!origin) return cb(null, true);
      if (allowedOrigins.has(origin)) return cb(null, true);
      return cb(new Error("CORS_NOT_ALLOWED"));
    },
    credentials: true, // Cookies'in paylaşıma izin verilmesi
  })
);
// JSON, URL encoded ve cookies'leri parse etme
app.use(express.json());  // JSON verisi almak için
app.use(express.urlencoded({ extended: true }));  // URL encoded veriler için
app.use(cookieParser());
app.use(requestContextMiddleware)  // Cookies'leri çözümlemek için


// API route'larını tanımlama
app.use("/api/users", userRoutesneedRefactor);  // User işlemleri
app.use("/api/deals", dealRoutes);  // Deal işlemleri
app.use("/api/auth", authRoutes);  // Auth işlemleri (login, register vs.)
app.use("/api/deal-votes", dealVoteRoutes);  // Deal oy işlemleri
app.use("/api/comments", commentRoutes);  // Comment işlemleri
app.use("/api/account", accountSettingsRoutes);  // Account settings işlemleri
app.use("/api/user", userRoutes);  // Kullanıcı işlemleri
app.use("/api/seller", sellerRoutes);  // Seller işlemleri
app.use("/api/vote", voteRoutes);  // Vote işlemleri
app.use("/api/comment-likes", commentLikeRoutes);  // Comment like işlemleri
app.use("/api/category", categoryRoutes);
app.use("/api/mod", modRoutes);
app.use("/api/uploads", uploadRoutes);
app.use("/api/badges", badgeRoutes);
app.use("/cache", cacheRoutes);

app.get("/api/openapi.json", (req, res) => {
  res.sendFile(path.join(__dirname, "docs", "openapi.json"));
});

app.get("/api/docs", (req, res) => {
  res.sendFile(path.join(__dirname, "docs", "swagger.html"));
});

async function startServer() {
  try {
    await ensureDealSearchIndex()
    await seedReferenceDataToRedis()
    await ensureDealIdCounter()
    const ttlDays = Number(process.env.REDIS_DEAL_TTL_DAYS) || 31
    await seedRecentDealsToRedis({ days: 31, ttlDays })
    await ensureCommentIdCounter()
  } catch (err) {
    console.error("Redis init skipped:", err?.message || err)
  }
  // Sunucuyu dinlemeye ba??la
  app.listen(3000, () => console.log("Server running on http://localhost:3000"));
}

startServer().catch((err) => {
  console.error("Server failed to start:", err?.message || err)
  process.exit(1)
})
