import { AggregateRoot, Result, UniqueID } from "@common/domain"; import { UserAuthenticatedEvent } from "../events"; import { EmailAddress, PasswordHash, Username } from "../value-objects"; export interface IAuthenticatedUserProps { username: Username; email: EmailAddress; passwordHash: PasswordHash; roles: string[]; token: string; } export class AuthenticatedUser extends AggregateRoot { static create(props: IAuthenticatedUserProps, id: UniqueID): Result { const user = new AuthenticatedUser(props, id); // 🔹 Disparar evento de dominio "UserAuthenticatedEvent" const { email } = props; user.addDomainEvent(new UserAuthenticatedEvent(id, email.toString())); return Result.ok(user); } private _hasRole(role: string): boolean { return (this._props.roles || []).some((r) => r === role); } comparePassword(plainPassword: string): Promise { return this._props.passwordHash.compare(plainPassword); } public getRoles(): string[] { return this._props.roles; } 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(), password: this._props.passwordHash.toString(), roles: this._props.roles.map((role) => role.toString()), token: this._props.token, }; } }