import { errorMiddleware } from "./middlewares/error";
import fileUpload from "express-fileupload";
import cookieParser from "cookie-parser";
import passport from "./config/passport";
import session from "express-session";
import express from "express";
import dotenv from "dotenv";
import cors from "cors";

import favicon from "serve-favicon";
import path from "path";

// Import all routers
// Auth and Social Auth routes
import socialAuthRouter from "./modules/auth/social/social.routes";
import accountRouter from "./modules/account/account.routes";
import authRouter from "./modules/auth/auth.routes";

// RBAC and Admin routes
import adminRouter from "./modules/admin/admin.routes";
import rbacRouter from "./modules/rbac/rbac.routes";

// Account new feature routers
import notificationRouter from "./modules/notification/notification.routes";
import activityRouter from "./modules/activities/activity.routes";
import followRouter from "./modules/follow/follow.routes";

// Product related routers
import productSuggestedFeatureRoutes from "./modules/features_suggestion/product.suggested.feature.routes";
import productAlternativeRoutes from "./modules/product_alternative/product.alternative.routes";
import productCategoryRoutes from "./modules/product_categorie/product.category.routes";
import productCommentRoutes from "./modules/comment/product.comment.routes";
import productGalleryRoutes from "./modules/gallery/product.gallery.routes";
import productTeamRoutes from "./modules/product_team/product.team.routes";
import productReviewRoutes from "./modules/review/product.review.routes";
import productUpdateRoutes from "./modules/update/product.update.routes";
import productFaqRoutes from "./modules/faq/product.faq.routes";
import productRoutes from "./modules/product/product.routes";
import contactRoutes from "./modules/contact/contact.routes";
import { createTables } from "./migrations/createTables";

const app = express();
dotenv.config({ path: ".env" });

// CORS configuration
const allowedOrigins = [
  process.env.FRONTEND_URL,
  process.env.DASHBOARD_URL,
].filter((origin): origin is string => !!origin);

app.use(
  cors({
    origin: function (origin, callback) {
      // Allow requests with no origin (like mobile apps or curl requests)
      if (!origin) return callback(null, true);

      if (allowedOrigins.indexOf(origin) === -1) {
        const msg = `The CORS policy for this site does not allow access from the specified Origin: ${origin}`;
        return callback(new Error(msg), false);
      }
      return callback(null, true);
    },
    credentials: true,
    methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
    allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
  }),
);

// Middleware
app.use(cookieParser());
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true, limit: "10mb" }));

// Trust proxy settings for secure cookies in production
app.set("trust proxy", 1);

// Session configuration for Passport
app.use(
  session({
    secret: process.env.SESSION_SECRET!,
    resave: false,
    saveUninitialized: false,
    cookie: {
      secure: process.env.NODE_ENV === "production",
      httpOnly: true,
      sameSite: "none",
      maxAge: 24 * 60 * 60 * 1000,
    },
  }),
);

// Session configuration
app.use(
  session({
    secret: process.env.SESSION_SECRET || "toolffy_session_secret_2026",
    resave: false,
    saveUninitialized: false,
    cookie: {
      secure: process.env.NODE_ENV === "production",
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000, // 24 hours
    },
  }),
);

// Passport middleware
app.use(passport.initialize());
app.use(passport.session());

// File upload
app.use(
  fileUpload({
    useTempFiles: true,
    tempFileDir: "/tmp/",
    createParentPath: true,
    limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
    abortOnLimit: true,
  }),
);

// Favicon
const faviconPath = path.join(__dirname, "..", "public", "favicon.ico");
app.use(favicon(faviconPath));

// Health check endpoint
app.get("/health", (req, res) => {
  res.status(200).json({
    success: true,
    message: "Server is healthy",
    timestamp: new Date().toISOString(),
    version: "1.0.0",
  });
});

// API Routes
// Auth and Social Auth routes
app.use("/api/v1/auth", authRouter);
app.use("/api/v1/social", socialAuthRouter);
app.use("/api/v1/account", accountRouter);

// RBAC and Admin routes
app.use("/api/v1/rbac", rbacRouter);
app.use("/api/v1/admin", adminRouter);

// Account new feature routers
app.use("/api/v1/follow", followRouter);
app.use("/api/v1/notifications", notificationRouter);
app.use("/api/v1/activities", activityRouter);

// app.use("/api/v1/product-categories", require("./routes/productCategoryRoutes").default);

// Product category routes
app.use("/api/v1/product-categories", productCategoryRoutes);
// Product routes
app.use("/api/v1/products", productRoutes);
// Product comment routes
app.use("/api/v1/comments", productCommentRoutes);
// Product review routes
app.use("/api/v1/reviews", productReviewRoutes);
// Product gallery routes
app.use("/api/v1/gallery", productGalleryRoutes);
// Product update routes
app.use("/api/v1/updates", productUpdateRoutes);
// Product FAQ routes
app.use("/api/v1/faqs", productFaqRoutes);
// Product suggested features routes
app.use("/api/v1/features/suggestions", productSuggestedFeatureRoutes);
// Product Alternative routes
app.use("/api/v1/product-alternatives", productAlternativeRoutes);
// Product Team routes
app.use("/api/v1/product-teams", productTeamRoutes);
// Contact routes
app.use("/api/v1/contact", contactRoutes);

// Initialize database tables
createTables();

// Error middleware (should be last)
app.use(errorMiddleware);

export default app;
