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

// Helper to check if logged in
const isLoggedIn = (req) => !!req.session.user_id;

router.get('/me', (req, res) => {
  if (!isLoggedIn(req)) return res.json({ authenticated: false });
  res.json({
    authenticated: true,
    user: {
      id: req.session.user_id,
      full_name: req.session.full_name || '',
      email: req.session.email || '',
      role: req.session.role || ''
    }
  });
});

router.post('/login', async (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) return res.status(400).json({ error: 'Email and password required' });
  try {
    const user = await db.fetch('SELECT id, full_name, email, password, role FROM users WHERE email = ?', [email]);
    if (!user || !(await bcrypt.compare(password, user.password))) {
      return res.status(401).json({ error: 'Invalid email or password' });
    }
    req.session.user_id = user.id;
    req.session.full_name = user.full_name;
    req.session.email = user.email;
    req.session.role = user.role;
    res.json({ success: true, user: { id: user.id, full_name: user.full_name, email: user.email, role: user.role } });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.post(['/register', '/send-verification'], async (req, res) => {
  const { full_name, email, password } = req.body;
  if (!full_name || !email || !password) return res.status(400).json({ error: 'All fields required' });
  if (password.length < 6) return res.status(400).json({ error: 'Password must be at least 6 characters' });
  
  try {
    const existing = await db.fetch('SELECT id FROM users WHERE email = ?', [email]);
    if (existing) return res.status(409).json({ error: 'Email already registered' });
    
    const hash = await bcrypt.hash(password, 10);
    const insertId = await db.insert('INSERT INTO users (full_name, email, password, role, email_verified) VALUES (?, ?, ?, ?, 1)', [full_name, email, hash, 'Viewer']);
    
    req.session.user_id = insertId;
    req.session.full_name = full_name;
    req.session.email = email;
    req.session.role = 'Viewer';
    
    res.json({ success: true, user: { id: insertId, full_name, email, role: 'Viewer' } });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/logout', (req, res) => {
  req.session.destroy();
  res.json({ success: true });
});

router.post('/forgot-password', async (req, res) => {
  const { email } = req.body;
  if (!email) return res.status(400).json({ error: 'Email required' });
  
  try {
    const user = await db.fetch('SELECT id, full_name FROM users WHERE email = ?', [email]);
    if (!user) return res.json({ success: true, message: 'If the email exists, a reset link has been sent.' });
    
    const token = crypto.randomBytes(32).toString('hex');
    const expires = new Date(Date.now() + 3600000).toISOString().slice(0, 19).replace('T', ' ');
    await db.query('INSERT INTO password_reset_tokens (user_id, token, expires_at) VALUES (?, ?, ?)', [user.id, token, expires]);
    
    // In a real app, send email here using nodemailer
    // For now, assume success as per PHP original
    res.json({ success: true, message: 'If the email exists, a reset link has been sent.' });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/reset-password', async (req, res) => {
  const { token, password } = req.body;
  if (!token || !password) return res.status(400).json({ error: 'Token and password required' });
  if (password.length < 6) return res.status(400).json({ error: 'Password must be at least 6 characters' });
  
  try {
    const row = await db.fetch('SELECT user_id FROM password_reset_tokens WHERE token = ? AND expires_at > NOW() AND used = 0', [token]);
    if (!row) return res.status(400).json({ error: 'Invalid or expired reset token' });
    
    const hash = await bcrypt.hash(password, 10);
    await db.query('UPDATE users SET password = ? WHERE id = ?', [hash, row.user_id]);
    await db.query('UPDATE password_reset_tokens SET used = 1 WHERE token = ?', [token]);
    
    res.json({ success: true, message: 'Password reset successfully.' });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
