import { Result } from "@repo/rdx-utils";
import { isPossiblePhoneNumber, parsePhoneNumberWithError } from "libphonenumber-js";
import { z } from "zod/v4";
import { translateZodValidationError } from "../helpers";
import { ValueObject } from "./value-object";

interface PhoneNumberProps {
  value: string;
}

export class PhoneNumber extends ValueObject<PhoneNumberProps> {
  static validate(value: string) {
    const schema = z
      .string()
      .optional()
      .default("")
      .refine(
        (value: string) => (value === "" ? true : isPossiblePhoneNumber(value, "ES")),
        "Please specify a valid phone number (include the international prefix)."
      );
    /*.transform((value: string) => {
        console.log("transforming value", value);

        if (value === "") return "";

        try {
          const phoneNumber = parsePhoneNumberWithError(value, "ES");
          return phoneNumber.formatInternational();
        } catch (error) {
          console.log(error);
          if (error instanceof ParseError) {
            // Not a phone number, non-existent country, etc.
            console.log(error.message);
          } else {
            return error;
          }

          return phoneNumber;
        }
      })*/

    return schema.safeParse(value, {
      reportInput: true,
    });
  }

  static create(value: string): Result<PhoneNumber> {
    const valueIsValid = PhoneNumber.validate(value);

    if (!valueIsValid.success) {
      return Result.fail(
        translateZodValidationError("PhoneNumber creation failed", valueIsValid.error)
      );
    }

    return Result.ok(new PhoneNumber({ value: valueIsValid.data }));
  }

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

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

  toString() {
    return String(this.props.value);
  }

  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;
  }
}
