<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Cart\LegacyOrderImport;

final class LegacyAddressNormalizer
{
    public const int MAX_PHONE_LENGTH = 12;
    public const int MAX_VAT_ID_LENGTH = 16;

    public function phone(mixed $value): ?string
    {
        $raw = $this->nullableString($value);
        if (null === $raw) {
            return null;
        }

        $normalized = preg_replace('/[^0-9+]/', '', $raw) ?? '';
        if (str_starts_with($normalized, '00')) {
            $normalized = '+'.mb_substr($normalized, 2);
        }

        // Common French international notation: +33 (0)3 ...
        $normalized = preg_replace('/^\+330/', '+33', $normalized) ?? $normalized;

        if (1 === preg_match('/^\+?[0-9]+$/D', $normalized)) {
            return $this->truncate($normalized, self::MAX_PHONE_LENGTH);
        }

        return $this->truncate($raw, self::MAX_PHONE_LENGTH);
    }

    public function vatId(mixed $value): ?string
    {
        $vatId = $this->nullableString($value);
        if (null === $vatId) {
            return null;
        }

        $vatId = mb_strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $vatId) ?? '');

        return $this->truncate($vatId, self::MAX_VAT_ID_LENGTH);
    }

    private function nullableString(mixed $value): ?string
    {
        if (null === $value) {
            return null;
        }

        $value = mb_trim((string) $value);

        return '' === $value ? null : $value;
    }

    private function truncate(string $value, int $maxLength): string
    {
        return mb_substr($value, 0, $maxLength);
    }
}
