/**
 * User Domain Model
 * Pure domain entity with business logic validation
 */
class User {
  constructor(id, name, email, password, createdAt, updatedAt) {
    this.id = id;
    this.name = name;
    this.email = email;
    this.password = password;
    this.createdAt = createdAt;
    this.updatedAt = updatedAt;
  }

  /**
   * Factory method to create a new User
   * @param {Object} data - { name, email, password }
   * @returns {User}
   */
  static create(data) {
    const { name, email, password } = data;

    // Validation
    if (!name || name.trim().length === 0) {
      throw new Error('User name is required');
    }

    if (!email || !User.isValidEmail(email)) {
      throw new Error('Valid email is required');
    }

    if (!password || password.length < 6) {
      throw new Error('Password must be at least 6 characters long');
    }

    return new User(null, name.trim(), email.toLowerCase(), password, new Date(), new Date());
  }

  /**
   * Email validation
   * @param {string} email 
   * @returns {boolean}
   */
  static isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  }

  /**
   * Update user name
   * @param {string} newName 
   */
  updateName(newName) {
    if (!newName || newName.trim().length === 0) {
      throw new Error('User name is required');
    }
    this.name = newName.trim();
    this.updatedAt = new Date();
  }

  /**
   * Get user without sensitive data
   * @returns {Object}
   */
  toPublicJSON() {
    return {
      id: this.id,
      name: this.name,
      email: this.email,
      createdAt: this.createdAt,
      updatedAt: this.updatedAt
    };
  }
}

module.exports = User;
