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

function requireAdmin(req, res, next) {
  const db = getDb();
  const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.session.userId);
  if (!user || user.role !== 'admin') return res.status(403).send('Alleen voor admins');
  next();
}

router.get('/', requireAdmin, (req, res) => {
  const db = getDb();
  const users = db.prepare('SELECT id, username, email, role, created_at FROM users ORDER BY username').all();
  res.render('user-list', { users, user: { username: req.session.username } });
});

router.get('/new', requireAdmin, (req, res) => {
  res.render('user-form', { editUser: null, error: null });
});

router.post('/new', requireAdmin, (req, res) => {
  const db = getDb();
  const { username, password, email, role } = req.body;
  if (!username || !password) return res.render('user-form', { editUser: null, error: 'Gebruikersnaam en wachtwoord zijn verplicht' });
  const existing = db.prepare('SELECT id FROM users WHERE username = ?').get(username);
  if (existing) return res.render('user-form', { editUser: null, error: 'Gebruikersnaam bestaat al' });
  const hash = bcrypt.hashSync(password, 10);
  const result = db.prepare('INSERT INTO users (username, password_hash, email, role) VALUES (?, ?, ?, ?)').run(username, hash, email || '', role || 'viewer');
  db.prepare('INSERT INTO user_settings (user_id) VALUES (?)').run(result.lastInsertRowid);
  logAudit(req.session.userId, req.session.username, 'user_created', 'user', result.lastInsertRowid, `Gebruiker ${username} aangemaakt`);
  res.redirect('/users');
});

router.get('/:id/edit', requireAdmin, (req, res) => {
  const db = getDb();
  const editUser = db.prepare('SELECT id, username, email, role FROM users WHERE id = ?').get(req.params.id);
  if (!editUser) return res.redirect('/users');
  res.render('user-form', { editUser, error: null });
});

router.post('/:id/edit', requireAdmin, (req, res) => {
  const db = getDb();
  const { username, password, email, role } = req.body;
  const editUser = db.prepare('SELECT id, username, email, role FROM users WHERE id = ?').get(req.params.id);
  if (!editUser) return res.redirect('/users');
  if (password && password.trim()) {
    const hash = bcrypt.hashSync(password, 10);
    db.prepare('UPDATE users SET username=?, password_hash=?, email=?, role=? WHERE id=?').run(username, hash, email || '', role, req.params.id);
  } else {
    db.prepare('UPDATE users SET username=?, email=?, role=? WHERE id=?').run(username, email || '', role, req.params.id);
  }
  logAudit(req.session.userId, req.session.username, 'user_updated', 'user', req.params.id, `Gebruiker ${username} bijgewerkt`);
  res.redirect('/users');
});

router.post('/:id/delete', requireAdmin, (req, res) => {
  const db = getDb();
  if (Number(req.params.id) === Number(req.session.userId)) return res.redirect('/users');
  db.prepare('DELETE FROM users WHERE id = ?').run(req.params.id);
  res.redirect('/users');
});

module.exports = router;
