<?php

declare(strict_types=1);

namespace App\Service\Whatsapp;

final class PhoneNumberNormalizer
{
    public function normalizeToE164NoPlus(?string $phone): ?string
    {
        if ($phone === null) {
            return null;
        }

        $value = trim($phone);
        if ($value === '') {
            return null;
        }

        $hasPlus = str_starts_with($value, '+');
        $digits = preg_replace('/\D+/', '', $value) ?: '';
        if ($digits === '') {
            return null;
        }

        if ($hasPlus) {
            return $this->validInternationalNumber($digits) ? $digits : null;
        }

        if (str_starts_with($digits, '00')) {
            $digits = substr($digits, 2);

            return $this->validInternationalNumber($digits) ? $digits : null;
        }

        if (preg_match('/^6\d{8}$/', $digits) === 1) {
            return '237'.$digits;
        }

        if (preg_match('/^06\d{8}$/', $digits) === 1) {
            return '237'.substr($digits, 1);
        }

        if (str_starts_with($digits, '237') && preg_match('/^2376\d{8}$/', $digits) === 1) {
            return $digits;
        }

        return $this->validInternationalNumber($digits) ? $digits : null;
    }

    public function toContactChatId(?string $phone): ?string
    {
        $normalized = $this->normalizeToE164NoPlus($phone);

        return $normalized ? $normalized.'@c.us' : null;
    }

    private function validInternationalNumber(string $digits): bool
    {
        return preg_match('/^[1-9]\d{10,14}$/', $digits) === 1;
    }
}
