<?php

declare(strict_types=1);

namespace App\EventListener;

use App\Entity\Document;
use App\Service\DocumentStorageService;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\ORM\Events;
use Psr\Log\LoggerInterface;

#[AsEntityListener(event: Events::postRemove, method: 'postRemove', entity: Document::class)]
class DocumentFileCleanupListener
{
    public function __construct(
        private readonly DocumentStorageService $storageService,
        private readonly ?LoggerInterface $logger = null,
    ) {}

    public function postRemove(Document $document): void
    {
        $path = $document->getPath();

        // Do not attempt file deletion for Base64 data URIs
        if ($this->storageService->isBase64DataUri($path)) {
            return;
        }

        $deleted = $this->storageService->delete($path);

        if ($deleted) {
            $this->logger?->info('Document file deleted from disk', [
                'documentId' => $document->getId(),
                'path'       => $path,
            ]);
        } else {
            $this->logger?->warning('Document file not found on disk during cleanup', [
                'documentId' => $document->getId(),
                'path'       => $path,
            ]);
        }
    }
}
