<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Checkout\Phone;

use InPost\International\Checkout\Exception\InvalidPhoneNumberException;
use InPost\International\Country;
use InPost\International\Delivery\Util\PhoneNumberResolver;
use Symfony\Contracts\Translation\TranslatorInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class PhoneNumberValidator implements PhoneNumberValidatorInterface
{
    /**
     * @var PhoneNumberResolver
     */
    private $resolver;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    public function __construct(PhoneNumberResolver $resolver, TranslatorInterface $translator)
    {
        $this->resolver = $resolver;
        $this->translator = $translator;
    }

    /**
     * @throws InvalidPhoneNumberException
     */
    public function validate(\Address $address): void
    {
        $phone = $this->resolver->resolve($address);

        if (null === $phone) {
            throw new InvalidPhoneNumberException($this->translator->trans('Phone number is required', [], 'Modules.Inpostinternational.Validators'));
        }

        if (null === $prefix = $phone->getPrefix()) {
            throw new InvalidPhoneNumberException($this->translator->trans('Could not determine phone country code', [], 'Modules.Inpostinternational.Validators'));
        }

        if (null === $country = Country::getByPhoneNumberPrefix($prefix)) {
            throw new InvalidPhoneNumberException($this->translator->trans('Phone country code "{code}" is not supported by the carrier', ['{code}' => $prefix], 'Modules.Inpostinternational.Validators'));
        }

        if (!preg_match($country->getPhoneNumberPattern(), $phone->getNumber())) {
            throw new InvalidPhoneNumberException($this->translator->trans('Phone number is invalid', [], 'Modules.Inpostinternational.Validators'));
        }
    }
}
