<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\EventListener\Doctrine\Attendance;

use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\ORM\Events;
use Ferienpass\CoreBundle\Application\ExtraFileManager;
use Ferienpass\CoreBundle\Entity\AttendanceExtraFile;

/**
 * Keeps the object storage in step with the database: whenever a file answer row
 * disappears — replaced by a new upload, deleted by an admin, pruned as an
 * abandoned staged upload, or cascaded away with its attendance — the stored
 * bytes go with it.
 *
 * postRemove (not preRemove) so a failed flush cannot delete bytes that are still
 * referenced.
 */
#[AsEntityListener(event: Events::postRemove, entity: AttendanceExtraFile::class)]
class AttendanceExtraFileListener
{
    public function __construct(private readonly ExtraFileManager $files)
    {
    }

    public function postRemove(AttendanceExtraFile $file): void
    {
        $this->files->deleteBytes($file);
    }
}
