const bcrypt = require('bcryptjs');
const { validationResult } = require('express-validator');
const userModel = require('../models/userModel');

function showLogin(req, res) {
  res.render('auth/login', { title: 'Login', layout: 'auth/layout' });
}

async function login(req, res) {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    req.flash('error', 'Enter a valid email and password.');
    return res.redirect('/login');
  }
  const { email, password } = req.body;
  const user = await userModel.findByEmail(email);
  if (!user || !(await bcrypt.compare(password, user.password_hash))) {
    req.flash('error', 'Invalid login credentials.');
    return res.redirect('/login');
  }
  req.session.user = { id: user.id, name: user.name, email: user.email, role: user.role };
  return res.redirect('/dashboard');
}

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

function showChangePassword(req, res) {
  res.render('auth/change-password', { title: 'Change Password' });
}

async function changePassword(req, res) {
  const { current_password, new_password, confirm_password } = req.body;
  if (!new_password || new_password.length < 8 || new_password !== confirm_password) {
    req.flash('error', 'New password must be at least 8 characters and match confirmation.');
    return res.redirect('/change-password');
  }
  const user = await userModel.findByEmail(req.session.user.email);
  if (!user || !(await bcrypt.compare(current_password, user.password_hash))) {
    req.flash('error', 'Current password is incorrect.');
    return res.redirect('/change-password');
  }
  await userModel.updatePassword(user.id, await bcrypt.hash(new_password, 12));
  req.flash('success', 'Password changed successfully.');
  return res.redirect('/dashboard');
}

module.exports = { showLogin, login, logout, showChangePassword, changePassword };
