import { DomainEntity, EmailAddress, UniqueID } from "@/core/common/domain";
import { Result } from "@repo/rdx-utils";

export interface IJWTPayloadProps {
  tabId: UniqueID;
  userId: UniqueID;
  email: EmailAddress;
}

export interface IJWTPayloadPrimitives {
  tab_id: string;
  user_id: string;
  email: string;
}

export interface IJWTPayload {
  tabId: UniqueID;
  userId: UniqueID;
  email: EmailAddress;

  toPersistenceData(): any;
}

export class JWTPayload extends DomainEntity<IJWTPayloadProps> implements IJWTPayload {
  static create(props: IJWTPayloadProps): Result<JWTPayload, Error> {
    return Result.ok(new JWTPayload(props));
  }

  static createFromPrimitives(values: IJWTPayloadPrimitives): Result<JWTPayload, Error> {
    const { email, user_id, tab_id } = values;
    const emailOrError = EmailAddress.create(email);
    const userIdOrError = UniqueID.create(user_id, false);
    const tabIdOrError = UniqueID.create(tab_id, false);

    const result = Result.combine([emailOrError, userIdOrError, tabIdOrError]);

    if (result.isFailure) {
      return Result.fail(result.error);
    }

    return JWTPayload.create({
      email: emailOrError.data,
      userId: userIdOrError.data,
      tabId: tabIdOrError.data,
    });
  }

  get tabId(): UniqueID {
    return this.props.tabId;
  }

  get userId(): UniqueID {
    return this.props.userId;
  }

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

  toPersistenceData(): any {
    return {
      tab_id: this.tabId.toString(),
      user_id: this.userId.toString(),
      email: this.email.toString(),
    };
  }
}
