<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop\src\Http;

use Plugin\tnt_stabila_shop\src\Repositories\SentrySpoolRepository;
use Sentry\HttpClient\HttpClientInterface;
use Sentry\HttpClient\Request;
use Sentry\HttpClient\Response;
use Sentry\Options;

/**
 * Sentry HTTP client that spools instead of sending.
 *
 * The SDK builds the complete envelope (body) and would normally POST it to the DSN endpoint
 * synchronously, inside the shop request. This implementation persists the envelope to the
 * local spool table and returns a synthetic success response, so a capture never touches the
 * network on the request path — in any environment, with no fpm/module dependency. The
 * tnt_stabila_sentry_spool cron replays the spooled envelopes out-of-band via the SDK's real
 * client (see {@see \Plugin\tnt_stabila_shop\src\Services\SentrySpoolFlusher}).
 */
final class SpoolingHttpClient implements HttpClientInterface
{
    /** Returned to the SDK so it treats the capture as accepted (HTTP 202, like Sentry ingest). */
    private const ACCEPTED = 202;

    public function __construct(private readonly SentrySpoolRepository $spool)
    {
    }

    public function sendRequest(Request $request, Options $options): Response
    {
        $body = $request->getStringBody();
        if ($body !== null && $body !== '') {
            $this->spool->spool($body);
        }

        return new Response(self::ACCEPTED, [], '');
    }
}
