/**
 * src/arabic/phone.ts
 * أدوات أرقام الهاتف السعودية — Saudi phone number utilities
 */
import { z } from 'zod';
import { createChildLogger } from '../utils/logger.js';
const log = createChildLogger('arabic:phone');
// Saudi mobile prefixes: 05x (where x = 0,3,4,5,6,7,8,9)
const SAUDI_MOBILE_RE = /^\+9665[0345789]\d{7}$/;
/**
 * Normalize any Saudi phone input to +9665xxxxxxxx format.
 * Handles: 05xx, +9665xx, 9665xx, 005xx, 00966xxx
 */
export function normalizeSaudiPhone(input) {
    if (!input)
        return null;
    // Strip all non-digit chars except leading +
    const hasPlus = input.trim().startsWith('+');
    const digits = input.replace(/\D/g, '');
    let normalized = null;
    if (digits.startsWith('00966') && digits.length === 14) {
        // 009665xxxxxxxx → +9665xxxxxxxx
        normalized = `+${digits.slice(2)}`;
    }
    else if (digits.startsWith('966') && digits.length === 12) {
        // 9665xxxxxxxx or +9665xxxxxxxx
        normalized = `+${digits}`;
    }
    else if (digits.startsWith('05') && digits.length === 10) {
        // 05xxxxxxxx → +9665xxxxxxxx
        normalized = `+966${digits.slice(1)}`;
    }
    else if (digits.startsWith('5') && digits.length === 9) {
        // 5xxxxxxxx → +9665xxxxxxxx
        normalized = `+966${digits}`;
    }
    if (normalized && SAUDI_MOBILE_RE.test(normalized)) {
        return normalized;
    }
    log.debug({ input, normalized }, 'Phone normalization failed or invalid');
    return null;
}
/**
 * Validate if a phone number is a valid Saudi mobile number.
 */
export function isValidSaudiPhone(phone) {
    const normalized = normalizeSaudiPhone(phone);
    return normalized !== null;
}
/**
 * Format a Saudi phone number for human-readable display: 05xx xxx xxxx
 */
export function formatForDisplay(phone) {
    const normalized = normalizeSaudiPhone(phone);
    if (!normalized)
        return phone; // Return as-is if can't normalize
    // +9665xxxxxxxx → 05xx xxx xxxx
    const local = `0${normalized.slice(4)}`; // +966 → 0
    return `${local.slice(0, 4)} ${local.slice(4, 7)} ${local.slice(7)}`;
}
// ─── Zod schema for validation in routes ────────────────────────────
export const saudiPhoneSchema = z.string().transform((val, ctx) => {
    const normalized = normalizeSaudiPhone(val);
    if (!normalized) {
        ctx.addIssue({
            code: z.ZodIssueCode.custom,
            message: 'رقم هاتف سعودي غير صالح',
        });
        return z.NEVER;
    }
    return normalized;
});
//# sourceMappingURL=phone.js.map