<?php

declare(strict_types=1);

namespace App\State\Provider\Dolibarr;

use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Service\Dolibarr\DolibarrApiService;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\Response;

/**
 * Custom provider pour les DolibarrAccounts récupérés via l'api dolibarr.
 */
final readonly class DolibarrDocDownloadProvider implements ProviderInterface
{
    public function __construct(
        private DolibarrApiService $dolibarrApiService,
    ) {
    }

    /**
     * @param mixed[] $uriVariables
     * @param mixed[] $context
     */
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): Response
    {
        if ($operation instanceof GetCollection) {
            throw new \RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
        }

        $data = $this->dolibarrApiService->downloadBillingDocPdf(
            $uriVariables['dolibarrDocType'],
            $uriVariables['ref']
        );

        // Build the response and attach the file to it
        // @see https://symfony.com/doc/current/components/http_foundation.html#serving-files
        $response = new Response(base64_decode($data['content']));

        $response->headers->set('Charset', 'UTF-8');
        $response->headers->set('Access-Control-Expose-Headers', 'Content-Disposition');
        $response->headers->set('Content-Type', $data['content-type']);

        $response->headers->set(
            'Content-Disposition',
            HeaderUtils::makeDisposition(HeaderUtils::DISPOSITION_ATTACHMENT, $data['filename'])
        );

        return $response;
    }
}
