<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Validator;

use Gls\GlsPoland\DataProvider\ParcelShopDataProvider;
use Gls\GlsPoland\Translation\TranslatorAwareTrait;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

final class ParcelShopIdValidator extends ConstraintValidator
{
    use TranslatorAwareTrait;

    private $dataProvider;

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

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

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

        if (!is_scalar($value) && (!is_object($value) || !method_exists($value, '__toString'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $value = (string) $value;

        try {
            $parcelShop = $this->dataProvider->getParcelShop($value);
        } catch (\Exception $e) {
            $this->context
                ->buildViolation($this->getTranslator()->trans('Could not verify ParcelShop validity.', [], 'Modules.Glspoland.Errors'))
                ->addViolation();

            return;
        }

        if (null === $parcelShop) {
            $message = $this->getTranslator()->trans('ParcelShop "#id#" does not exist.', ['#id#' => $value], 'Modules.Glspoland.Errors');

            $this->context
                ->buildViolation($message)
                ->addViolation();
        }
    }
}
