
// Load WebServer
import {
    default as express
} from "express";

// Load Templating Engine
import {
    default as nunjucks
} from "nunjucks";

import {
    router
} from "express-file-routing"

const {
    User,
    Group
} = await import("./lib/database/connect.mjs");

import sessions from "express-session";

// Initialize WebServer
const expressApp = express();
const expressPort = 3000;

// Configure Templating Engine
nunjucks.configure('./', {
    autoescape: false,
    express: expressApp,
    noCache: true
});

// Enable Express Sessions
expressApp.use(sessions({
    secret: 'keyboard cat',
    resave: false,
    rolling: true,
    saveUninitialized: false,
    cookie: { 
        secure: false,
        maxAge: 1800 * 1000,
        httpOnly: true
    }
}))

// Enable Cross Origins
expressApp.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
    next();
});

// Mount Middlewares to WebServer
expressApp.use(express.urlencoded());
expressApp.use(express.json());
expressApp.use(express.static('./static/'))
expressApp.use((request, response, next) => {
    request.getAuthState = () => {
        if (!request.session && !request.session.authState) {
            return 'unauthenticated';
        } else {
            return request.session.authState;
        }
    }
    request.setAuthState = (newState) => {
        request.session.authState = newState;
        request.session.save();
    }
    request.getUser = async () => {
        return await User.findByPk(request.session.userid);
    }
    next();
})
expressApp.use("/", await router())

// Server starten
expressApp.listen(expressPort, () => {
    console.log(`Server is listening on port ${expressPort}`);
});
