<?php

declare(strict_types=1);

namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Entity\MileageAllowance;
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 MileageAllowanceAmountReceiptDownloadProvider 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
    {
        $mileageAllowance = $this->entityManager->find(MileageAllowance::class, $uriVariables['id']);

        if (null === $mileageAllowance) {
            throw new NotFoundHttpException('Mileage allowance not found.');
        }

        $receiptPath = $mileageAllowance->getAmountReceiptPath();

        if (null === $receiptPath) {
            throw new NotFoundHttpException('No amount receipt found for this mileage allowance.');
        }

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

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

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

        return $response;
    }
}
