import { normalizePhone } from "./utils";

const COUNTRY_RULES = [
  { countryCode: "249", nationalLength: 9 },
  { countryCode: "966", nationalLength: 9 },
  { countryCode: "971", nationalLength: 9 },
  { countryCode: "968", nationalLength: 8 }
] as const;

export type SponsorPhoneIdentity = {
  phone: string;
  loginUsername: string;
  countryCode: (typeof COUNTRY_RULES)[number]["countryCode"];
};

export function sponsorPhoneIdentity(value: string): SponsorPhoneIdentity | null {
  const phone = normalizePhone(value);
  if (!phone) return null;

  const digits = phone.slice(1);
  const rule = COUNTRY_RULES.find(({ countryCode }) => digits.startsWith(countryCode));
  if (!rule) return null;

  const nationalNumber = digits.slice(rule.countryCode.length);
  if (nationalNumber.length !== rule.nationalLength || !/^\d+$/.test(nationalNumber)) {
    return null;
  }

  return {
    phone,
    loginUsername: `0${nationalNumber}`,
    countryCode: rule.countryCode
  };
}

export function isSponsorLoginUsername(value: string): boolean {
  return /^0\d{8,9}$/.test(value.trim());
}
