import { Result } from "@repo/rdx-utils";
import { Maybe } from "@repo/rdx-utils";
import { isValidPhoneNumber, parsePhoneNumberWithError } from "libphonenumber-js";
import { z } from "zod";
import { ValueObject } from "./value-object";

interface PhoneNumberProps {
  value: string;
}

export class PhoneNumber extends ValueObject<PhoneNumberProps> {
  static create(value: string): Result<PhoneNumber> {
    const valueIsValid = PhoneNumber.validate(value);

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

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

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

  static validate(value: string) {
    const schema = z
      .string()
      .refine(
        isValidPhoneNumber,
        "Please specify a valid phone number (include the international prefix)."
      )
      .transform((value: string) => parsePhoneNumberWithError(value).number.toString());
    return schema.safeParse(value);
  }

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

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

  getCountryCode(): string | undefined {
    return parsePhoneNumberWithError(this.props.value).country;
  }

  getNationalNumber(): string {
    return parsePhoneNumberWithError(this.props.value).nationalNumber;
  }

  getNumber(): string {
    return parsePhoneNumberWithError(this.props.value).number.toString();
  }

  getExtension(): string | undefined {
    return parsePhoneNumberWithError(this.props.value).ext;
  }
}
