const express = require("express");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");

const app = express();

app.use(bodyParser.json());

const generateToken = (user) => {
    return jwt.sign({ user }, "hello kitty", { expiresIn: "1h" })
}

const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(" ")[1];

    if (token == null)
        return res.sendStatus(401);

    jwt.verify(token, "hello kitty", (error, user) => {
        if (error)
            return res.sendStatus(401);

        req.user = user;
        next();
    })
}

app.post('/jwt-login', (req, res) => {
    const { username, password } = req.body;
    if (username == "admin" && password == "password") {
        const user = { id: 1, username };
        const accessToken = generateToken(user);
        res.json(accessToken);
    } else {
        res.status(401).send("Invaild credentials")
    }
})

app.post("/jwt-logout", authenticateToken, (req, res) => {
    res.send("Logged out successful");
})

app.get("/jwt-profile", authenticateToken, (req, res) => {
    res.send(`Welcome ${req.user.user.username}`)
})

app.listen(3000, (error) => {
    if (error)
        console.log(error);
    console.log("Server is running: http://localhost:3000");
})