import express from "express";
import mustache from "mustache";
import bodyParse from "body-parser";
import cookieSession from "cookie-session";
import { readdirSync, readFileSync } from "fs";
import { randomUUID } from "crypto";

const app = express();
app.use(express.static("./static"));
app.use(bodyParse.urlencoded({ extended: true }));
app.use(bodyParse.json());
app.use(cookieSession({
    name: "session",
    keys: ["-JX$9fGF#S6qSzJn"],
    maxAge: 31 * 24 * 60 * 60 * 1000
}));
const port = 9999;

const templates = new Map(readdirSync("./templates").map(fn => [fn, readFileSync(`./templates/${fn}`, "utf-8")]));

app.get("/", (req, res) => {
    if (!req.session.isPopulated && !req.session.nonce) {
        return res.redirect("/login");
    }

    const nonce = req.session.nonce;
    res.send(mustache.render(templates.get("mainPage.html"), {nonce}));
});

app.get("/login", (req, res) => {
    const nonce = randomUUID();
    req.session = {
        nonce
    };
    res.send(mustache.render(templates.get("loginPage.html"), {nonce}));
});

app.get("/authCallback", (req, res) => {
    const nonce = req.session.nonce;
    if (req.query.tg_passport) {
        res.redirect("/");
    } else {
        res.send({error: true});
    }
});

app.listen(port, () => console.log(`⚡️ Serving on port ${port}`));