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

router.get('/wachtwoord-vergeten', (req, res) => {
  res.render('forgot-password', { error: null, success: null });
});

router.post('/wachtwoord-vergeten', (req, res) => {
  const db = getDb();
  const { email } = req.body;
  if (!email) return res.render('forgot-password', { error: 'Voer je e-mailadres in', success: null });
  const user = db.prepare('SELECT * FROM users WHERE email = ?').get(email);
  if (!user) return res.render('forgot-password', { error: null, success: 'Als dit e-mailadres bekend is, ontvang je een reset-link' });
  const token = crypto.randomBytes(32).toString('hex');
  const expires = new Date(Date.now() + 3600000).toISOString();
  db.prepare('UPDATE users SET reset_token = ?, reset_expires = ? WHERE id = ?').run(token, expires, user.id);
  console.log(`[WACHTWOORD-RESET] Link voor ${email}: ${process.env.BASE_URL || 'http://192.168.1.247:3000'}/wachtwoord-reset/${token}`);
  res.render('forgot-password', { error: null, success: 'Als dit e-mailadres bekend is, ontvang je een reset-link' });
});

router.get('/wachtwoord-reset/:token', (req, res) => {
  const db = getDb();
  const user = db.prepare('SELECT * FROM users WHERE reset_token = ? AND reset_expires > datetime(\'now\')').get(req.params.token);
  if (!user) return res.render('forgot-password', { error: 'Ongeldige of verlopen reset-link', success: null });
  res.render('reset-password', { token: req.params.token, error: null });
});

router.post('/wachtwoord-reset/:token', (req, res) => {
  const db = getDb();
  const { password, password2 } = req.body;
  if (!password || password.length < 6) return res.render('reset-password', { token: req.params.token, error: 'Wachtwoord moet minimaal 6 tekens zijn' });
  if (password !== password2) return res.render('reset-password', { token: req.params.token, error: 'Wachtwoorden komen niet overeen' });
  const user = db.prepare('SELECT * FROM users WHERE reset_token = ? AND reset_expires > datetime(\'now\')').get(req.params.token);
  if (!user) return res.render('forgot-password', { error: 'Ongeldige of verlopen reset-link', success: null });
  const hash = bcrypt.hashSync(password, 10);
  db.prepare('UPDATE users SET password_hash = ?, reset_token = \'\', reset_expires = \'\' WHERE id = ?').run(hash, user.id);
  res.redirect('/login?reset=1');
});

module.exports = router;
