<?php

/**
 * @author Colinet Julien
 */
declare(strict_types=1);

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\MediaBundle\Trait;

use Doctrine\ORM\Mapping as ORM;
use Serenity\MediaBundle\Entity\Media;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

trait MediaMandatoryTrait
{
    #[Assert\Valid]
    #[ORM\OneToOne(targetEntity: Media::class, cascade: ['all'])]
    #[ORM\JoinColumn(name: 'media_id', referencedColumnName: 'id', onDelete: 'SET NULL')]
    private ?Media $media = null;

    public function getMedia(): ?Media
    {
        return $this->media;
    }

    public function setMedia(?Media $media): void
    {
        if (null === $media) {
            return;
        }

        if (!$media->getUploadedFile() && !$media->getFile()->getName()) {
            $this->media = null;

            return;
        }
        $this->media = $media;
    }

    #[Assert\Callback]
    public function validate(ExecutionContextInterface $context, $payload): void
    {
        if (!$this->getMedia() || (!$this->getMedia()->getFile() && !$this->getMedia()->getUploadedFile())) {
            $context->buildViolation('This value should not be blank.')
              ->atPath('media.uploadedFile')
              ->addViolation();
        }
    }
}
