<?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\Delivery\Validator;

use InPost\International\Api\Exception\ApiClientExceptionInterface;
use InPost\International\Api\Point\Model\PointCapability;
use InPost\International\Delivery\Point\PointDataProviderInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

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

final class DeliveryPointIdValidator extends ConstraintValidator
{
    /**
     * @var PointDataProviderInterface
     */
    private $dataProvider;

    public function __construct(PointDataProviderInterface $dataProvider)
    {
        $this->dataProvider = $dataProvider;
    }

    public function validate($value, Constraint $constraint): void
    {
        if (!$constraint instanceof DeliveryPointId) {
            throw new UnexpectedTypeException($constraint, DeliveryPointId::class);
        }

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

        if (!is_string($value)) {
            throw new UnexpectedTypeException($value, 'string');
        }

        try {
            $point = $this->dataProvider->getPoint($value);
        } catch (ApiClientExceptionInterface $e) {
            $this->context
                ->buildViolation('Could not fetch point data from the API.')
                ->setTranslationDomain('Modules.Inpostinternational.Validators')
                ->addViolation();

            return;
        }

        if (null === $point) {
            $this->context
                ->buildViolation('Point "{{ id }}" does not exist.')
                ->setParameter('{{ id }}', $value)
                ->setTranslationDomain('Modules.Inpostinternational.Validators')
                ->addViolation();
        } elseif (!$point->hasCapability(PointCapability::ParcelCollect())) {
            $this->context
                ->buildViolation('Point "{{ id }}" does not support parcel collection.')
                ->setParameter('{{ id }}', $value)
                ->setTranslationDomain('Modules.Inpostinternational.Validators')
                ->addViolation();
        } elseif (null !== $constraint->country && $constraint->country->value !== $point->getCountry()) {
            $this->context
                ->buildViolation('Point "{{ id }}" is located in a different country than the selected delivery country.')
                ->setParameter('{{ id }}', $value)
                ->setTranslationDomain('Modules.Inpostinternational.Validators')
                ->addViolation();
        }
    }
}
