<?php

declare(strict_types=1);

namespace App\EventListener;

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

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

    public function prePersist(Document $document): void
    {
        $this->compressIfPdf($document);
    }

    public function preUpdate(Document $document): void
    {
        $this->compressIfPdf($document);
    }

    private function compressIfPdf(Document $document): void
    {
        if ('application/pdf' !== $document->getMimeType()) {
            return;
        }

        $path = $document->getPath();

        if ($this->storageService->isBase64DataUri($path)) {
            // Legacy Base64 path
            $result = $this->pdfCompressor->compressBase64Pdf($path);
            if (null === $result) {
                return;
            }
            $document->setPath($result['path']);
            $document->setSize($result['size']);
        } else {
            // File-based path
            $absolutePath = $this->storageService->getAbsolutePath($path);
            $result       = $this->pdfCompressor->compressFile($absolutePath);
            if (null === $result) {
                return;
            }
            $document->setSize($result['size']);
        }

        $this->logger?->info('PDF compressed', [
            'document'       => $document->getName(),
            'originalSize'   => $result['originalSize'],
            'compressedSize' => $result['size'],
            'saved'          => $result['saved'],
        ]);
    }
}
