<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\DocStoreBundle\Validator\Constraints;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Entity\StoredObjectVersion;
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

final class AsyncFileExistsValidator extends ConstraintValidator
{
    public function __construct(
        private readonly StoredObjectManagerInterface $storedObjectManager,
    ) {}

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

        if (null === $value) {
            return;
        }
        if ($value instanceof StoredObjectVersion) {
            $this->validateObject($value, $constraint);
        } elseif ($value instanceof StoredObject) {
            $this->validateObject($value->getCurrentVersion(), $constraint);
        } else {
            throw new \Symfony\Component\Form\Exception\UnexpectedTypeException($value, StoredObjectVersion::class);
        }
    }

    protected function validateObject(StoredObjectVersion $file, AsyncFileExists $constraint): void
    {
        if (!$this->storedObjectManager->exists($file)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ filename }}', $file->getFilename())
                ->addViolation();
        }
    }
}
