<?php

declare(strict_types=1);

namespace App\Module\ProjectManagement\Infrastructure\EventListener;

use App\Module\ProjectManagement\Domain\Entity\TaskDocument;
use Doctrine\ORM\Event\PreRemoveEventArgs;
use Psr\Log\LoggerInterface;

class TaskDocumentListener
{
    public function __construct(
        private readonly string $uploadDir,
        private readonly LoggerInterface $logger,
    ) {}

    public function preRemove(TaskDocument $document, PreRemoveEventArgs $event): void
    {
        // Un lien vers le partage SMB ne possède pas de fichier sur disque : rien à nettoyer.
        if ($document->isShareLink()) {
            return;
        }

        $filePath = $this->uploadDir.'/'.$document->getFileName();

        if (file_exists($filePath)) {
            if (!unlink($filePath)) {
                $this->logger->warning('Failed to delete document file: {path}', ['path' => $filePath]);
            }
        } else {
            $this->logger->warning('Document file not found on disk: {path}', ['path' => $filePath]);
        }
    }
}
