<?php

namespace App\Controller;

use App\Repository\DevisRepository;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[IsGranted('ROLE_USER')]
class DevisPdfController extends AbstractController
{
    public function __construct(
        private LoggerInterface $logger,
    ) {
    }

    #[Route('/uploads/devis/{id}/{type}', name: 'app_devis_pdf', methods: ['GET'], requirements: ['type' => 'unsigned|signed|audit'])]
    public function __invoke(
        int $id,
        string $type,
        DevisRepository $devisRepository,
        #[Autowire('%kernel.project_dir%')] string $projectDir,
    ): Response {
        $devis = $devisRepository->find($id);

        if (null === $devis) {
            throw $this->createNotFoundException('Devis introuvable.');
        }

        $this->checkAccess();

        $filename = match ($type) {
            'unsigned' => $devis->getUnsignedPdf(),
            'signed' => $devis->getSignedPdf(),
            'audit' => $devis->getAuditPdf(),
            default => null,
        };

        if (null === $filename) {
            throw $this->createNotFoundException('Document non disponible.');
        }

        $path = $projectDir.'/public/uploads/devis/'.$filename;

        if (!file_exists($path)) {
            throw $this->createNotFoundException('Fichier introuvable.');
        }

        $downloadName = $type.'-'.str_replace(['/', '\\'], '-', $devis->getOrderNumber()->getNumOrder()).'.pdf';

        $response = new BinaryFileResponse($path);
        $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $downloadName);
        $response->headers->set('Content-Type', 'application/pdf');

        return $response;
    }

    private function checkAccess(): void
    {
        if (!$this->isGranted('ROLE_EMPLOYE')) {
            $this->logger->warning('DevisPdf: acces non-employe par '.$this->getUser()?->getUserIdentifier());
        }
    }
}
