// controllers/authController.js
const authService = require('../services/authService');

const login = async (req, res) => {
  try {
    const { email, password } = req.body;
    
    if (!email || !password) {
      return res.status(400).json({ error: 'Email and password are required' });
    }
    
    const result = await authService.login(email, password);
    
    if (result.error) {
      return res.status(401).json({ error: result.error });
    }
    
    res.status(200).json({
      message: 'Login successful',
      user: result.user,
      token: result.token
    });
  } catch (error) {
    console.error('Login error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

const register = async (req, res) => {
  try {
    const { email, password, firstName, lastName, userType } = req.body;
    
    if (!email || !password || !firstName || !lastName || !userType) {
      return res.status(400).json({ error: 'All fields are required' });
    }
    
    const result = await authService.register(email, password, firstName, lastName, userType, req.tenantId);
    
    if (result.error) {
      return res.status(400).json({ error: result.error });
    }
    
    res.status(201).json({
      message: 'Registration successful',
      user: result.user
    });
  } catch (error) {
    console.error('Registration error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

const logout = async (req, res) => {
  try {
    // In a real implementation, you might invalidate the JWT token
    res.status(200).json({ message: 'Logout successful' });
  } catch (error) {
    console.error('Logout error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

const getCurrentUser = async (req, res) => {
  try {
    // This would use middleware to verify JWT and extract user info
    res.status(200).json({ user: req.user });
  } catch (error) {
    console.error('Get current user error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

module.exports = {
  login,
  register,
  logout,
  getCurrentUser
};