import cors from "cors";
import express from "express";
import helmet from "helmet";
import morgan from "morgan";
import path from "node:path";
import { fileURLToPath } from "node:url";
import authRoutes from "./routes/auth.routes.js";
import applicationRoutes from "./routes/application.routes.js";
import reportRoutes from "./routes/report.routes.js";
import transactionRoutes from "./routes/transaction.routes.js";
import notaryRoutes from "./routes/notary.routes.js";
import taxRuleRoutes from "./routes/taxRule.routes.js";
import auditRoutes from "./routes/audit.routes.js";
import staffRoutes from "./routes/staff.routes.js";
import settingRoutes from "./routes/setting.routes.js";
import publicRoutes from "./routes/public.routes.js";

const app = express();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const publicDir = path.resolve(__dirname, "../public");

app.use(helmet());
app.use(cors());
app.use(express.json({ limit: "2mb" }));
app.use(morgan("dev"));
app.use(express.static(publicDir));
app.use("/uploads", express.static(path.resolve(__dirname, "../uploads"), {
  setHeaders: (res) => {
    res.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
  }
}));

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

app.use("/api/auth", authRoutes);
app.use("/api/applications", applicationRoutes);
app.use("/api/transactions", transactionRoutes);
app.use("/api/reports", reportRoutes);
app.use("/api/notaries", notaryRoutes);
app.use("/api/tax-rules", taxRuleRoutes);
app.use("/api/audit-logs", auditRoutes);
app.use("/api/staff", staffRoutes);
app.use("/api/settings", settingRoutes);
app.use("/api/public", publicRoutes);
app.get("*", (req, res, next) => {
  if (req.path.startsWith("/api/")) {
    return next();
  }
  return res.sendFile(path.join(publicDir, "index.html"));
});

app.use((err, _req, res, _next) => {
  console.error(err);
  res.status(500).json({ message: "Server error" });
});

export default app;
