const express = require("express");
const session = require("express-session");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const crypto = require("crypto");
const path = require("path");
const moment = require("moment");
require("dotenv").config();
const log = require("node-file-logger");

const app = express();
const port = process.env.PORT;

const cors = require('cors');

// Konfiguration: Erlaube Frontend-Port
app.use(cors({
  origin: 'http://localhost:5173',
  credentials: true // Wenn du Cookies / Sessions brauchst (z.B. JWT in Cookies)
}));

const options = {
  timeZone: "europe/Berlin",
  folderPath: "./logs/",
  dateBasedFileNaming: true,
  fileNamePrefix: "DailyLogs_",
  fileNameExtension: ".log",
  dateFormat: "YYYY_MM_DD",
  timeFormat: "H:mm:ss",
};
log.SetUserOptions(options);

// Middleware
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());

app.use(express.urlencoded({ extended: false }));

// Session-Konfiguration
app.use(
  session({
    secret: process.env.SESSIONSECRET,
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 1000 * 60 * 60 * 24 * 2 },
  })
);

const userRoutes = require("./routes/user");
const spieleRoutes = require("./routes/spiele");
const featureRoutes = require("./routes/feature");
const memberRoutes = require("./routes/member");
const trainingRoutes = require("./routes/training");
const anwesendRoutes = require("./routes/anwesend");

app.use(
  "/:abteilung?/user",
  (req, res, next) => {
    req.abteilung = req.params.abteilung; // `abteilung` in req speichern
    next();
  },
  userRoutes
);
app.use(
  "/:abteilung?/spiele",
  (req, res, next) => {
    req.abteilung = req.params.abteilung; // `abteilung` in req speichern
    next();
  },
  spieleRoutes
);
app.use(
  "/:abteilung?/feature",
  (req, res, next) => {
    req.abteilung = req.params.abteilung; // `abteilung` in req speichern
    next();
  },
  featureRoutes
);
app.use(
  "/:abteilung?/member",
  (req, res, next) => {
    req.abteilung = req.params.abteilung; // `abteilung` in req speichern
    next();
  },
  memberRoutes
);
app.use(
  "/:abteilung/training",
  (req, res, next) => {
    req.abteilung = req.params.abteilung;
    next();
  },
  trainingRoutes
);
app.use(
  "/:abteilung/anwesend",
  (req, res, next) => {
    req.abteilung = req.params.abteilung;
    next();
  },
  anwesendRoutes
);

const server = app.listen(port, "0.0.0.0", () => {
  console.log(`Server is running on ${process.env.HOST}:${port}/`);
  log.Info(`Server is running on ${process.env.HOST}:${port}/`);
});
