import { COUNTRIES_PHONE_CODES } from '../../../constans/countriesPhoneCodes';
import { Country } from '../../../constans/country';

/**
 * Returns a phone number with a new country code.
 *
 * @param phone Old phone number
 * @param from Code that used byt old phone number
 * @param to A new code that should be applied to the phone number
 */
export function replacePhoneCode(phone: string | undefined, from: Country | undefined, to: Country): string {
  const toCode = COUNTRIES_PHONE_CODES[to] ?? '';
  if (!phone) {
    return toCode;
  }

  if (!from) {
    return `${toCode}${phone.substring(toCode.length)}`;
  }

  const fromCode = COUNTRIES_PHONE_CODES[from];

  if (phone.startsWith(fromCode)) {
    const regExp = new RegExp(`^${fromCode.replace('+', '\\+')}`);
    return phone.replace(regExp, toCode);
  }

  return `${toCode}${phone.substring(fromCode.length)}`;
}
