const User = require('../models/User');
const Restaurant = require('../models/Restaurant');
const jwt = require('jsonwebtoken');

const generateToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: '30d',
  });
};

exports.register = async (req, res) => {
  try {
    const { name, email, phoneNumber, password, role, gstNo, restaurantName, location } = req.body;

    const userExists = await User.findOne({ email });
    if (userExists) {
      return res.status(400).json({ message: 'User already exists' });
    }

    let certificateImage = '';
    if (role === 'owner' && req.file) {
      certificateImage = req.file.path.replace(/\\/g, '/'); // Normalize path
    }

    const userData = {
      name,
      email,
      phoneNumber,
      password,
      role: role || 'user',
    };

    if (role === 'owner') {
      userData.gstNo = gstNo;
      userData.restaurantName = restaurantName;
      userData.location = location;
      userData.certificateImage = certificateImage;
    }

    const user = await User.create(userData);

    // If role is owner, automatically create a restaurant listing
    if (user && role === 'owner') {
      await Restaurant.create({
        owner: user._id,
        name: restaurantName,
        location: location,
        image: 'https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?auto=format&fit=crop&q=80&w=1200', // Default image
        tables: [] // Empty tables initially
      });
    }

    if (user) {
      res.status(201).json({
        _id: user._id,
        name: user.name,
        email: user.email,
        role: user.role,
        token: generateToken(user._id),
      });
    }
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.login = async (req, res) => {
  try {
    const { email, password, role } = req.body;

    const user = await User.findOne({ email }).select('+password');

    if (user && (await user.comparePassword(password))) {
      // Check if role matches if provided
      if (role && user.role !== role) {
        return res.status(401).json({ message: `This account is not registered as a ${role}` });
      }

      res.json({
        _id: user._id,
        name: user.name,
        email: user.email,
        role: user.role,
        token: generateToken(user._id),
      });
    } else {
      res.status(401).json({ message: 'Invalid email or password' });
    }
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};