import { Email } from '../value-objects/Email';
import { Result, success, failure } from '../value-objects/Result';
import { ValidationError } from '../errors/DomainError';

export interface UserProps {
  id: string;
  email: Email;
  name: string;
  createdAt: Date;
  updatedAt: Date;
}

export class User {
  private constructor(private props: UserProps) {}

  static create(props: Omit<UserProps, 'createdAt' | 'updatedAt'> & {
    createdAt?: Date;
    updatedAt?: Date;
  }): Result<User, ValidationError> {
    if (!props.id || props.id.trim().length === 0) {
      return failure(new ValidationError('User ID is required'));
    }
    if (!props.name || props.name.trim().length < 2) {
      return failure(new ValidationError('Name must be at least 2 characters'));
    }

    const now = new Date();
    return success(
      new User({
        ...props,
        createdAt: props.createdAt ?? now,
        updatedAt: props.updatedAt ?? now,
      })
    );
  }

  getId(): string {
    return this.props.id;
  }

  getEmail(): Email {
    return this.props.email;
  }

  getName(): string {
    return this.props.name;
  }

  updateName(name: string): Result<void, ValidationError> {
    if (!name || name.trim().length < 2) {
      return failure(new ValidationError('Name must be at least 2 characters'));
    }
    this.props.name = name;
    this.props.updatedAt = new Date();
    return success(undefined);
  }

  toJSON() {
    return {
      id: this.props.id,
      email: this.props.email.getValue(),
      name: this.props.name,
      createdAt: this.props.createdAt,
      updatedAt: this.props.updatedAt,
    };
  }
}
