const express = require('express');
const sha256 = require("sha256");
const jwt = require('jsonwebtoken');
const { getConnection, getUserByUsername, addUser, getUser } = require('../libs/mysql');
const { checkAuth } = require('../libs/middlewares');

const router = express.Router();

router.post('/login', async (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
        return res.status(400).send({ error: 'Invalid username or password' });
    }

    const connection = await getConnection();
    const user = await getUserByUsername(connection, username);
    connection.end();
    if (user[0]) {
        if (user[0].password === sha256(password)) {
            const token = jwt.sign({ id: user[0].id }, process.env.JWT_SECRET, {
                expiresIn: 1000 * 60 * 60 * 24 * 7,
            });
            return res.send({ token: token });
        }
    }
    res.status(401).send({ error: 'Invalid username or password' });
});

router.post('/register', async (req, res) => {
    const { username, password } = req.body;
    const connection = await getConnection();

    if (!username || !password) {
        connection.end();
        return res.status(400).send({ error: 'Invalid username or password' });
    }

    const user = await getUserByUsername(connection, username);
    if (user[0]) {
        connection.end();
        return res.status(401).send({ error: 'Username already exists' });
    }

    if (!/^[a-zA-Z0-9-_]+$/.test(username)) {
        connection.end();
        return res.status(400).send({ error: 'Invalid username' });
    }

    const hash = sha256(password);
    await addUser(connection, username, hash);
    connection.end();
    res.send({ message: 'User added' });
});

router.use('/me', checkAuth);
router.post('/me', async (req, res) => {
    const user = req.user;
    res.send({ id: user.id, username: user.username, admin: user.admin });  
});

module.exports = router;