<?php

namespace App\Services;

use InvalidArgumentException;

class PhoneNormalizationService
{
    public function normalize(?string $countryCode, ?string $phoneNumber): ?array
    {
        if (blank($countryCode) || blank($phoneNumber)) {
            return null;
        }

        $countryCode = $this->sanitizeCountryCode($countryCode);
        $digits = preg_replace('/\D+/', '', (string) $phoneNumber) ?? '';

        if ($digits === '') {
            throw new InvalidArgumentException(__('validation.phone_invalid'));
        }

        $e164 = '+'.$countryCode.$digits;

        if (! $this->isValidE164($e164)) {
            throw new InvalidArgumentException(__('validation.phone_invalid'));
        }

        return [
            'phone_country_code' => $countryCode,
            'phone_number' => $digits,
            'phone_e164' => $e164,
        ];
    }

    public function hasValidPhone(?string $phoneE164): bool
    {
        return filled($phoneE164) && $this->isValidE164($phoneE164);
    }

    private function sanitizeCountryCode(string $countryCode): string
    {
        return ltrim(preg_replace('/\D+/', '', $countryCode) ?? '', '0');
    }

    private function isValidE164(string $e164): bool
    {
        return (bool) preg_match('/^\+[1-9]\d{7,14}$/', $e164);
    }
}
