// backend/controllers/authController.js
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import User from '../models/User.js';

export const register = async (req, res) => {
  const { email, password, first_name, last_name, organization, address, city, state, zip_code, phone } = req.body;
  // Input validation
  if (!email || !password || !first_name || !last_name) {
    return res.status(400).json({ message: 'Required fields are missing' });
  }
  try {
    // Check for existing user by email
    const existingUser = await User.findByEmail(email);
    if (existingUser) {
      return res.status(400).json({ message: 'Email is already registered' });
    }
    // Hash the password before storing it
    const password_hash = await bcrypt.hash(password, 10);
    // Prepare user data for insertion
    const userData = {
      email,
      password_hash,
      organization: organization || null,
      first_name,
      last_name,
      address: address || null,
      city: city || null,
      state: state || null,
      zip_code: zip_code || null,
      phone: phone || null,
    };
    // Insert user into database
    await User.createUser(userData);
    res.status(201).json({ message: 'User registered successfully' });
  } catch (error) {
    console.error('Error registering user:', error.sqlMessage || error.message);
    res.status(500).json({ message: 'Error registering user. Please try again later.' });
  }
};

export const login = async (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    return res.status(400).json({ message: 'Email and password are required' });
  }
  try {
    // Find user by email
    const user = await User.findByEmail(email);
    if (!user) {
      return res.status(401).json({ message: 'Invalid credentials' });
    }
    // Compare passwords
    const isMatch = await bcrypt.compare(password, user.password_hash);
    if (!isMatch) {
      return res.status(401).json({ message: 'Invalid credentials' });
    }
    // Generate JWT token
    const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '1h' });
    res.json({
      token,
      expiresIn: 3600,
      message: 'Login successful',
    });
  } catch (error) {
    console.error('Error logging in user:', error);
    res.status(500).json({ message: 'Error logging in. Please try again later.' });
  }
};

