<?php

declare(strict_types=1);

namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Entity\Formation;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

final readonly class FormationJustificatifDownloadProvider implements ProviderInterface
{
    public function __construct(
        private EntityManagerInterface $entityManager,
        #[Autowire('%kernel.project_dir%/var/uploads')]
        private string $uploadDir,
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): BinaryFileResponse
    {
        $formation = $this->entityManager->find(Formation::class, $uriVariables['id']);

        if (null === $formation) {
            throw new NotFoundHttpException('Formation not found.');
        }

        $justificatifPath = $formation->getJustificatifPath();

        if (null === $justificatifPath) {
            throw new NotFoundHttpException('No justificatif found for this formation.');
        }

        $absolutePath = sprintf('%s/%s', $this->uploadDir, $justificatifPath);

        if (!file_exists($absolutePath)) {
            throw new NotFoundHttpException('Justificatif file not found.');
        }

        $response    = new BinaryFileResponse($absolutePath);
        $disposition = HeaderUtils::makeDisposition(
            HeaderUtils::DISPOSITION_ATTACHMENT,
            $formation->getJustificatifName() ?? 'justificatif.pdf'
        );
        $response->headers->set('Content-Disposition', $disposition);

        return $response;
    }
}
