<?php

namespace CpCreation\VitiCore\Behavior\Impl;

use CpCreation\VitiCore\Media\Model\File;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\HasLifecycleCallbacks]
trait Files
{
    #[ORM\ManyToMany(
        targetEntity: File::class,
        cascade: ['persist', 'remove']
    )]
    #[Assert\Valid]
    private Collection $files;

    public function addFile(File $file): void
    {
        if (!$this->files->contains($file)) {
            $this->files->add($file);
        }
    }

    public function removeFile(File $file): void
    {
        $this->files->removeElement($file);
    }

    /**
     * @return Collection<int, File>
     */
    public function getFiles(): Collection
    {
        return $this->files;
    }

    #[ORM\PrePersist]
    public function generateFileCollectionIfEmpty(): void
    {
        if (!isset($this->files)) {
            $this->files = new ArrayCollection();
        }
    }
}
