<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Validator;

use Gls\GlsPoland\AdePlus\ClientFactoryInterface;
use Gls\GlsPoland\AdePlus\Services\GetAllowed;
use Gls\GlsPoland\AdePlus\UserCredentialsInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

final class AdeUserCredentialsValidator extends ConstraintValidator
{
    private $clientFactory;

    public function __construct(ClientFactoryInterface $clientFactory)
    {
        $this->clientFactory = $clientFactory;
    }

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

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

        if (!$value instanceof UserCredentialsInterface) {
            throw new UnexpectedTypeException($value, UserCredentialsInterface::class);
        }

        try {
            $this->clientFactory
                ->create($constraint->sandbox, $value)
                ->servicesGetAllowed(new GetAllowed());
        } catch (\Exception $e) {
            // TODO messages by fault code
            $this->context
                ->buildViolation($e->getMessage())
                ->addViolation();
        }
    }
}
