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

/**
 * User Service
 * Business logic for user management
 */

/**
 * Get user profile by ID
 * @param {string} userId - User ID
 * @returns {Promise<Object>} User profile data
 */
const getUserProfile = async (userId) => {
  const user = await User.findByPk(userId, {
    attributes: [
      'id',
      'uid',
      'nickname',
      'avatar',
      'language',
      'balance',
      'invitationCode',
      'status',
      'createdAt',
      'updatedAt',
    ],
  });

  if (!user) {
    const error = new Error('User not found');
    error.statusCode = 404;
    error.code = 'USER_NOT_FOUND';
    throw error;
  }

  return user;
};

/**
 * Update user profile
 * @param {string} userId - User ID
 * @param {Object} updateData - Profile data to update
 * @returns {Promise<Object>} Updated user profile
 */
const updateUserProfile = async (userId, updateData) => {
  const user = await User.findByPk(userId);

  if (!user) {
    const error = new Error('User not found');
    error.statusCode = 404;
    error.code = 'USER_NOT_FOUND';
    throw error;
  }

  // Only allow updating nickname and avatar
  const allowedFields = ['nickname', 'avatar'];
  const filteredData = {};
  
  allowedFields.forEach(field => {
    if (updateData[field] !== undefined) {
      filteredData[field] = updateData[field];
    }
  });

  await user.update(filteredData);

  // Return updated user with only essential fields
  return {
    id: user.id,
    uid: user.uid,
    nickname: user.nickname,
    avatar: user.avatar,
    language: user.language,
    balance: user.balance,
    invitationCode: user.invitationCode,
    status: user.status,
    updatedAt: user.updatedAt,
  };
};

/**
 * Set user language preference
 * @param {string} userId - User ID
 * @param {string} language - Language code (zh, en, es)
 * @returns {Promise<Object>} Updated user profile
 */
const setUserLanguage = async (userId, language) => {
  const user = await User.findByPk(userId);

  if (!user) {
    const error = new Error('User not found');
    error.statusCode = 404;
    error.code = 'USER_NOT_FOUND';
    throw error;
  }

  // Validate language code
  const validLanguages = ['zh', 'en', 'es'];
  if (!validLanguages.includes(language)) {
    const error = new Error('Invalid language code. Must be one of: zh, en, es');
    error.statusCode = 400;
    error.code = 'INVALID_LANGUAGE';
    throw error;
  }

  await user.update({ language });

  return {
    id: user.id,
    language: user.language,
    updatedAt: user.updatedAt,
  };
};

module.exports = {
  getUserProfile,
  updateUserProfile,
  setUserLanguage,
};
