/**
 * Normalizes a phone number to standard digits-only format.
 * E.g., removes spaces, dashes, +, leading zeros for local prefixes.
 */
export function normalizePhoneNumber(rawPhone?: string | null): string {
  if (!rawPhone) return '';
  const digitsOnly = rawPhone.replace(/[^\d]/g, '').trim();
  if (!digitsOnly) return '';

  // Zimbabwe local format: 07... (10 digits) -> standard 2637...
  if (digitsOnly.startsWith('0') && digitsOnly.length === 10) {
    return `263${digitsOnly.substring(1)}`;
  }
  return digitsOnly;
}

/**
 * Returns all possible variations of a phone number (local, international, with +, without +).
 */
export function getPhoneNumberVariants(rawPhone?: string | null): string[] {
  if (!rawPhone) return [];
  const cleaned = rawPhone.replace(/[^\d+]/g, '').trim();
  const digitsOnly = cleaned.replace(/^\+/, '');
  const variants = new Set<string>();

  if (cleaned) variants.add(cleaned);
  if (digitsOnly) {
    variants.add(digitsOnly);
    variants.add(`+${digitsOnly}`);
  }

  // Zimbabwe local format: 07... (10 digits) <-> 2637...
  if (digitsOnly.startsWith('0') && digitsOnly.length === 10) {
    const withoutZero = digitsOnly.substring(1);
    variants.add(`263${withoutZero}`);
    variants.add(`+263${withoutZero}`);
    variants.add(`0${withoutZero}`);
  } else if (digitsOnly.startsWith('263') && digitsOnly.length === 12) {
    const local = `0${digitsOnly.substring(3)}`;
    variants.add(local);
    variants.add(digitsOnly);
    variants.add(`+${digitsOnly}`);
  }

  return Array.from(variants);
}

/**
 * Validates whether a given phone number is the system's reserved WhatsApp number.
 */
export function isSystemPhoneNumber(phone?: string | null): boolean {
  if (!phone) return false;
  const systemPhone = process.env.SELLER_WHATSAPP_NUMBER;
  if (!systemPhone) return false;

  const normalizedInput = normalizePhoneNumber(phone);
  const normalizedSystem = normalizePhoneNumber(systemPhone);

  if (normalizedInput === normalizedSystem) return true;

  const inputVariants = getPhoneNumberVariants(phone);
  const systemVariants = getPhoneNumberVariants(systemPhone);

  return inputVariants.some((v) => systemVariants.includes(v));
}

/**
 * Checks if a phone number matches any registered Business contact phone in the database
 */
export async function isBusinessContactPhone(
  phone: string | null | undefined,
  prisma: any,
  excludeBusinessId?: string,
): Promise<boolean> {
  if (!phone) return false;
  const inputNormalized = normalizePhoneNumber(phone);
  if (!inputNormalized) return false;

  const variants = getPhoneNumberVariants(phone);

  // 1. Direct query with variants (fast index lookup)
  const whereClause: any = {
    contactPhone: { in: variants },
  };
  if (excludeBusinessId) {
    whereClause.id = { not: excludeBusinessId };
  }

  const directMatch = await prisma.business.findFirst({
    where: whereClause,
  });
  if (directMatch) return true;

  // 2. Comprehensive check comparing normalized numbers across businesses
  const businesses = await prisma.business.findMany({
    where: excludeBusinessId ? { id: { not: excludeBusinessId } } : undefined,
    select: { id: true, contactPhone: true },
  });

  for (const biz of businesses) {
    if (biz.contactPhone) {
      const bizNormalized = normalizePhoneNumber(biz.contactPhone);
      if (bizNormalized && bizNormalized === inputNormalized) {
        return true;
      }
      const bizVariants = getPhoneNumberVariants(biz.contactPhone);
      if (variants.some((v) => bizVariants.includes(v))) {
        return true;
      }
    }
  }

  return false;
}

/**
 * Checks if a phone number is reserved for the system OR registered to any merchant/business
 */
export async function isReservedOrMerchantPhone(
  phone: string | null | undefined,
  prisma: any,
): Promise<{ isBlocked: boolean; reason?: string }> {
  if (!phone) return { isBlocked: false };

  if (isSystemPhoneNumber(phone)) {
    return {
      isBlocked: true,
      reason: 'This phone number is reserved for system platform operations and cannot be used as a customer number.',
    };
  }

  // Block only if the number is the system's own bot WhatsApp number (to prevent self-loops)
  return { isBlocked: false };
}

