import { AggregateRoot, EmailAddress, Result, UniqueID } from "@common/domain"; 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; hasRole(role: string): boolean; hasRoles(roles: string[]): boolean; getRoles(): string[]; toPersistenceData(): any; } export class User extends AggregateRoot implements IUser { static create(props: IUserProps, id: UniqueID): Result { 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"); } /** * 🔹 Devuelve una representación lista para persistencia */ toPersistenceData(): any { return { id: this.id.toString(), username: this.props.username.toString(), email: this.props.email.toString(), roles: this.props.roles.map((role) => role.toString()), }; } }