const User = require('../models/User');
const logger = require('../config/logger');

const getProfile = async (req, res, next) => {
  try {
    const user = await User.findByPk(req.user.id, {
      attributes: { exclude: ['password'] }
    });

    if (!user) {
      return res.status(404).json({
        status: 'error',
        message: 'User not found'
      });
    }

    res.json({
      status: 'success',
      data: { user }
    });
  } catch (error) {
    logger.error('Get profile error:', error);
    next(error);
  }
};

const updateProfile = async (req, res, next) => {
  const transaction = await sequelize.transaction();
  try {
    const { name, email } = req.body;
    const user = await User.findByPk(req.user.id, { transaction });

    if (!user) {
      await transaction.rollback();
      return res.status(404).json({
        status: 'error',
        message: 'User not found'
      });
    }

    if (email && email !== user.email) {
      const emailExists = await User.findOne({
        where: { email },
        transaction
      });

      if (emailExists) {
        await transaction.rollback();
        return res.status(409).json({
          status: 'error',
          message: 'Email already in use'
        });
      }
    }

    user.name = name || user.name;
    user.email = email || user.email;
    await user.save({ transaction });
    
    await transaction.commit();
    logger.info(`User profile updated: ${user.id}`);

    res.json({
      status: 'success',
      data: {
        user: {
          id: user.id,
          email: user.email,
          name: user.name,
          role: user.role
        }
      }
    });
  } catch (error) {
    await transaction.rollback();
    logger.error('Update profile error:', error);
    next(error);
  }
};

module.exports = { getProfile, updateProfile };