import { AggregateRoot, EmailAddress, UniqueID } from "@/core/common/domain";
import { Result } from "@repo/rdx-utils";
import { UserAuthenticatedEvent } from "../events";
import { Username } from "../value-objects";

export interface IUserProps {
  username: Username;
  email: EmailAddress;
  roles: string[];
}

export interface IUser {
  username: Username;
  email: EmailAddress;

  isUser: boolean;
  isAdmin: boolean;
  isActive: boolean;

  hasRole(role: string): boolean;
  hasRoles(roles: string[]): boolean;
  getRoles(): string[];
}

export class User extends AggregateRoot<IUserProps> implements IUser {
  static create(props: IUserProps, id: UniqueID): Result<User, Error> {
    const user = new User(props, id);

    // 🔹 Disparar evento de dominio "UserAuthenticatedEvent"
    const { email } = props;
    user.addDomainEvent(new UserAuthenticatedEvent(id, email.toString()));

    return Result.ok(user);
  }

  getRoles(): string[] {
    return this.props.roles;
  }

  hasRole(role: string): boolean {
    return (this.props.roles || []).some((r) => r === role);
  }

  hasRoles(roles: string[]): boolean {
    return roles.map((rol) => this.hasRole(rol)).some((value) => value != false);
  }

  get username(): Username {
    return this.props.username;
  }

  get email(): EmailAddress {
    return this.props.email;
  }

  get isUser(): boolean {
    return this.hasRole("user");
  }

  get isAdmin(): boolean {
    return this.hasRole("admin");
  }

  get isActive(): boolean {
    return true;
  }
}
