const express = require('express');
const bcrypt = require('bcrypt');
const Database = require('better-sqlite3');

const db = new Database('plusfit.db');
const router = express.Router();

router.get('/', (req, res) => {
    res.render('login');
});

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

    const admin = db
        .prepare('SELECT * FROM admins WHERE username = ?')
        .get(username);

    if (!admin) return res.send('Login fehlgeschlagen');

    const ok = await bcrypt.compare(password, admin.password);
    if (!ok) return res.send('Login fehlgeschlagen');

    req.session.loggedIn = true;
    res.redirect('/users/dashboard');
});

router.get('/logout', (req, res) => {
    req.session.destroy(() => res.redirect('/'));
});

module.exports = router;
