<?php

declare(strict_types=1);

namespace KupShop\UserBundle\Util;

use KupShop\KupShopBundle\Util\System\CurlUtil;
use KupShop\UserBundle\Dto\PhoneNumberValidationResult;
use KupShop\UserBundle\Exception\PhoneValidationException;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;

class PhoneNumberValidator
{
    protected string $host;

    public function __construct(
        protected CurlUtil $curlUtil,
        protected LoggerInterface $logger,
    ) {
        $this->host = isRunningOnCluster() ? 'http://phonenumber-validator.services' : 'http://phonenumber-validator.wpjshop.cz';
    }

    public function validate(string $phoneNumber, string $region = 'CZ'): PhoneNumberValidationResult
    {
        $payload = [
            'phone_number' => $phoneNumber,
            'region' => $region,
        ];

        try {
            $response = $this->curlUtil
                ->getClient(['Content-Type' => 'application/json'])
                ->request('POST', $this->host.'/validate', [
                    'body' => json_encode($payload),
                ])
                ->toArray();
        } catch (ExceptionInterface $e) {
            $this->logger->notice('Phone validation error', ['error' => $e->getMessage()]);
            throw new PhoneValidationException('Validation failed');
        }

        if ($response['valid'] === true) {
            return new PhoneNumberValidationResult($response['db_format'], $response['international_format'], $response['national_format']);
        }

        throw new PhoneValidationException('Phone number is not valid');
    }
}
