import { Result } from "@rdx/utils";
import { z } from "zod";
import { ValueObject } from "./value-object";

interface EmailAddressProps {
  value: string;
}

export class EmailAddress extends ValueObject<EmailAddressProps> {
  static create(value: string): Result<EmailAddress, Error> {
    const valueIsValid = EmailAddress.validate(value);

    if (!valueIsValid.success) {
      return Result.fail(new Error(valueIsValid.error.errors[0]?.message));
    }
    return Result.ok(new EmailAddress({ value: valueIsValid.data! }));
  }

  static createNullable(value?: string): Result<Maybe<EmailAddress>, Error> {
    if (!value || value.trim() === "") {
      return Result.ok(Maybe.none<EmailAddress>());
    }

    return EmailAddress.create(value).map((value) => Maybe.some(value));
  }

  private static validate(value: string) {
    const schema = z.string().email({ message: "Invalid email format" });
    return schema.safeParse(value);
  }

  getLocalPart(): string {
    return this.props.value.split("@")[0] ?? "";
  }

  getDomain(): string {
    return this.props.value.split("@")[1] ?? "";
  }

  getDomainExtension(): string {
    return this.getDomain().split(".")[1] ?? "";
  }

  getDomainName(): string {
    return this.getDomain().split(".")[0] ?? "";
  }

  getValue(): string {
    return this.props.value;
  }

  toPrimitive() {
    return this.getValue();
  }
}
