import { setupRoutes, uncheckedJwtRoutes } from './routes/router.js';
import { authenticateJwtCookie } from './authentication/middlewareAuthentication.js';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import { Database } from './database/database.js';
import { RouteError } from './routes/routeError.js';
import 'express-async-errors';

const app = express();

const logRequests = (req, res, next) => {
  console.log(req.method, req.originalUrl);
  next();
};

// Middleware functions
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
app.use(authenticateJwtCookie(uncheckedJwtRoutes));
app.use(logRequests);

// Database
const db = new Database();
await db.connect();

// Routes
app.use('/api', setupRoutes(db));

// Error handler
app.use((err, req, res, _) => {
  const routeError = RouteError.tryFrom(err);
  if (routeError) {
    res.status(routeError.code).json({ message: routeError.message });
  } else {
    res.status(500).end();
    console.error(err);
  }
});

const port = 80;
app.listen(port, () => {
  console.log(`Listening on port ${port}`);
});
