const router  = require('express').Router({ mergeParams: true });
const bcrypt  = require('bcryptjs');
const db      = require('../lib/db');

// ── Login ─────────────────────────────────────────────────────────────────────
router.get('/login', (req, res) => {
  if (req.session.userId) return res.redirect(`/${req.params.lang}/dashboard`);
  res.render('auth/login', { title: 'Sign In' });
});

router.post('/login', (req, res) => {
  const lang  = req.params.lang;
  const email = (req.body.email || '').toLowerCase().trim();
  const pass  = req.body.password || '';
  const user  = db.prepare('SELECT * FROM users WHERE email = ?').get(email);
  if (!user || !bcrypt.compareSync(pass, user.password)) {
    req.flash('error', 'Invalid email or password.');
    return res.redirect(`/${lang}/login`);
  }
  req.session.userId = user.id;
  res.redirect(`/${lang}/dashboard`);
});

// ── Signup ────────────────────────────────────────────────────────────────────
router.get('/signup', (req, res) => {
  if (req.session.userId) return res.redirect(`/${req.params.lang}/dashboard`);
  res.render('auth/signup', { title: 'Create Account' });
});

router.post('/signup', (req, res) => {
  const lang = req.params.lang;
  const { name, email, password } = req.body;
  if (!name || !email || !password || password.length < 6) {
    req.flash('error', 'Please fill all fields. Password min 6 chars.');
    return res.redirect(`/${lang}/signup`);
  }
  try {
    const hash = bcrypt.hashSync(password, 10);
    const r    = db.prepare('INSERT INTO users (name,email,password) VALUES (?,?,?)').run(name, email.toLowerCase().trim(), hash);
    req.session.userId = r.lastInsertRowid;
    res.redirect(`/${lang}/dashboard`);
  } catch {
    req.flash('error', 'Email already registered.');
    res.redirect(`/${lang}/signup`);
  }
});

// ── Logout ────────────────────────────────────────────────────────────────────
router.get('/logout', (req, res) => {
  const lang = req.params.lang;
  req.session.destroy(() => res.redirect(`/${lang}/`));
});

module.exports = router;
