import { FormErrorMessages } from "@/constants/Texts";
import { isValidE164Phone, normalizeToE164 } from "@/lib/phone/e164";
import type { CountryCode } from "libphonenumber-js";

type PhoneRulesOptions = {
  required?: boolean;
  defaultCountry?: CountryCode;
};

/** React Hook Form rules for an E.164 phone field. */
export function createPhoneFieldRules(options: PhoneRulesOptions = {}) {
  const { required = false, defaultCountry } = options;

  return {
    validate: (value: string | undefined) => {
      const trimmed = value?.trim() ?? "";
      if (!trimmed) {
        return required ? FormErrorMessages.required : true;
      }
      if (!isValidE164Phone(trimmed)) {
        return FormErrorMessages.invalidPhone;
      }
      return true;
    },
    setValueAs: (value: string | undefined) => {
      const trimmed = value?.trim() ?? "";
      if (!trimmed) return "";
      return normalizeToE164(trimmed, defaultCountry) ?? trimmed;
    },
  };
}

/** Normalize before API submit (defensive). */
export function normalizePhoneFieldValue(
  value: string | undefined,
  defaultCountry?: CountryCode,
): string | undefined {
  const trimmed = value?.trim();
  if (!trimmed) return undefined;
  return normalizeToE164(trimmed, defaultCountry) ?? undefined;
}
