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

// POST /api/spa/auth/login — JSON login, zet sessie
router.post('/login', (req, res) => {
  const { username, password } = req.body || {};
  if (!username || !password) {
    return res.status(400).json({ error: 'Gebruikersnaam en wachtwoord zijn verplicht' });
  }
  const db = getDb();
  const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
  if (!user || !bcrypt.compareSync(password, user.password_hash)) {
    return res.status(401).json({ error: 'Ongeldige gebruikersnaam of wachtwoord' });
  }
  req.session.userId = user.id;
  req.session.username = user.username;
  logAudit(user.id, user.username, 'user_login', 'user', user.id, `${user.username} ingelogd via SPA`);
  res.json({ id: user.id, username: user.username, role: user.role, email: user.email || '' });
});

// POST /api/spa/auth/logout
router.post('/logout', (req, res) => {
  req.session.destroy(() => {
    res.json({ ok: true });
  });
});

// GET /api/spa/auth/me — huidige gebruiker (ook voor sessie-check bij opstarten SPA)
router.get('/me', (req, res) => {
  if (!req.session || !req.session.userId) {
    return res.status(401).json({ error: 'Niet ingelogd' });
  }
  const db = getDb();
  const user = db.prepare('SELECT id, username, email, role FROM users WHERE id = ?').get(req.session.userId);
  if (!user) return res.status(401).json({ error: 'Niet ingelogd' });
  res.json(user);
});

module.exports = router;
