import "dotenv/config";
import express from "express";
import multer from "multer";
import cors from "cors";
import helmet from "helmet";
import morgan from "morgan";
import authRoutes from "./routes/authRoutes.js";
import productRoutes from "./routes/productRoutes.js";
import orderRoutes from "./routes/orderRoutes.js";
import publicClientReviewRoutes from "./routes/publicClientReviewRoutes.js";
import adminProductRoutes from "./routes/adminProductRoutes.js";
import adminOrderRoutes from "./routes/adminOrderRoutes.js";
import adminDashboardRoutes from "./routes/adminDashboardRoutes.js";
import adminUploadRoutes from "./routes/adminUploadRoutes.js";
import adminFrameShapeRoutes from "./routes/adminFrameShapeRoutes.js";
import adminBrandRoutes from "./routes/adminBrandRoutes.js";
import adminClientReviewRoutes from "./routes/adminClientReviewRoutes.js";
import adminBannerRoutes from "./routes/adminBannerRoutes.js";
import publicBannerRoutes from "./routes/publicBannerRoutes.js";
import adminProductTypeRoutes from "./routes/adminProductTypeRoutes.js";
import { uploadsRoot } from "./services/uploadPaths.js";
import { sendError } from "./utils/apiResponse.js";

const app = express();
const PORT = process.env.PORT || 8000;

const corsOrigins = process.env.FRONTEND_URL
  ? process.env.FRONTEND_URL.split(",").map((o) => o.trim())
  : true;
app.use(cors({ origin: corsOrigins, credentials: true }));
app.use(helmet({ crossOriginResourcePolicy: { policy: "cross-origin" } }));
app.use(morgan("dev"));
app.use(express.json({ limit: "1mb" }));
app.use("/uploads", express.static(uploadsRoot));

app.get("/api/health", (_req, res) => {
  res.json({ status: "ok" });
});

app.use("/api/auth", authRoutes);
app.use("/api/products", productRoutes);
app.use("/api/orders", orderRoutes);
app.use("/api/client-reviews", publicClientReviewRoutes);
app.use("/api/admin/products", adminProductRoutes);
app.use("/api/admin/orders", adminOrderRoutes);
app.use("/api/admin/dashboard", adminDashboardRoutes);
app.use("/api/admin/uploads", adminUploadRoutes);
app.use("/api/admin/frame-shapes", adminFrameShapeRoutes);
app.use("/api/admin/brands", adminBrandRoutes);
app.use("/api/admin/client-reviews", adminClientReviewRoutes);
app.use("/api/banners", publicBannerRoutes);
app.use("/api/admin/banners", adminBannerRoutes);
app.use("/api/admin/product-types", adminProductTypeRoutes);

app.use((_req, res) => {
  return sendError(res, 404, "NOT_FOUND", "Route not found.");
});

app.use(
  (
    err: unknown,
    _req: express.Request,
    res: express.Response,
    _next: express.NextFunction,
  ) => {
    console.error(err);

    if (err instanceof multer.MulterError) {
      return sendError(res, 400, "UPLOAD_ERROR", err.message);
    }

    if (
      err instanceof Error &&
      err.message === "Only image files are allowed."
    ) {
      return sendError(res, 400, "INVALID_FILE_TYPE", err.message);
    }

    return sendError(
      res,
      500,
      "INTERNAL_SERVER_ERROR",
      "Something went wrong.",
    );
  },
);

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
