const express = require('express');
const router = express.Router();
const { isAuthenticated } = require('../middleware/auth');
const { registerValidation, loginValidation } = require('../validators/auth');
const { validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
const { User } = require('../models');

// Login page
router.get('/login', (req, res) => {
  if (req.session.user) return res.redirect('/');
  res.render('auth/login', { title: 'Login' });
});

// Login post
router.post('/login', loginValidation, async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    req.flash('errors', errors.array().map(e => e.msg));
    return res.redirect('/login');
  }

  try {
    const { email, password } = req.body;
    const user = await User.findOne({ where: { email } });
    if (!user || !(await bcrypt.compare(password, user.password))) {
      req.flash('error', 'Invalid email or password.');
      return res.redirect('/login');
    }
    if (!user.isActive) {
      req.flash('error', 'Your account has been deactivated.');
      return res.redirect('/login');
    }

    req.session.user = {
      id: user.id,
      name: user.name,
      email: user.email,
      isAdmin: user.isAdmin,
      phone: user.phone,
    };
    await user.update({ lastLoginAt: new Date() });

    req.flash('success', 'Welcome back, ' + user.name + '!');
    const redirectTo = req.session.returnTo || '/';
    delete req.session.returnTo;
    res.redirect(redirectTo);
  } catch (error) {
    console.error('Login error:', error);
    req.flash('error', 'Something went wrong. Please try again.');
    res.redirect('/login');
  }
});

// Register page
router.get('/register', (req, res) => {
  if (req.session.user) return res.redirect('/');
  res.render('auth/register', { title: 'Register' });
});

// Register post
router.post('/register', registerValidation, async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    req.flash('errors', errors.array().map(e => e.msg));
    return res.redirect('/register');
  }

  try {
    const { name, email, password } = req.body;
    const existing = await User.findOne({ where: { email } });
    if (existing) {
      req.flash('error', 'Email already registered.');
      return res.redirect('/register');
    }

    const hashedPassword = await bcrypt.hash(password, 10);
    const user = await User.create({ name, email, password: hashedPassword });

    req.session.user = {
      id: user.id,
      name: user.name,
      email: user.email,
      isAdmin: false,
    };

    req.flash('success', 'Account created successfully!');
    res.redirect('/');
  } catch (error) {
    console.error('Register error:', error);
    req.flash('error', 'Something went wrong. Please try again.');
    res.redirect('/register');
  }
});

// Logout
router.get('/logout', (req, res) => {
  req.session.destroy();
  res.redirect('/');
});

module.exports = router;
