const User = require('../models/User');
const generateToken = require('../utils/generateToken');

// Register a new user
exports.signup = async (req, res) => {
  const { firstName, lastName, businessName, email, password } = req.body;
  const exists = await User.findOne({ email });
  if (exists) return res.status(400).json({ message: 'Email already in use' });
  const user = await User.create({ firstName, lastName, businessName, email, password });
  res.status(201).json({ _id: user._id, email: user.email, admin: user.admin, token: generateToken(user._id) });
};

// Authenticate user & get token
exports.signin = async (req, res) => {
  const { email, password } = req.body;
  const user = await User.findOne({ email });
  if (user && await user.verifyPassword(password)) {
    res.json({ _id: user._id, email: user.email, admin: user.admin, token: generateToken(user._id) });
  } else {
    res.status(401).json({ message: 'Invalid credentials' });
  }
};

exports.getUserProfile = async (req, res) => {
  try {
    const user = req.user; // set by protect()
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }
    res.json({
      _id:           user._id,
      firstName:     user.firstName,
      lastName:      user.lastName,
      businessName:  user.businessName,
      email:         user.email,
      admin:         user.admin
    });
  } catch (error) {
    console.error('Error fetching user profile:', error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Get all users (Admin only)
exports.getAllUsers = async (req, res) => {
  try {
    const users = await User.find({}).select('-password');
    res.json(users);
  } catch (error) {
    console.error('Error fetching users list:', error);
    res.status(500).json({ message: 'Server error' });
  }
};