const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const { getDb } = require('../db');

router.get('/login', (req, res) => {
  if (req.session.userId) return res.redirect('/');
  res.render('login', { error: null, reset: req.query.reset === '1' });
});

router.post('/auth/login', (req, res) => {
  const { username, password } = req.body;
  const db = getDb();
  const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
  if (!user || !bcrypt.compareSync(password, user.password_hash)) {
    return res.render('login', { error: 'Ongeldige gebruikersnaam of wachtwoord', reset: false });
  }
  req.session.userId = user.id;
  req.session.username = user.username;
  res.redirect('/');
});

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

module.exports = router;
