<?php

declare(strict_types=1);

namespace App\Shared\Infrastructure\Messenger;

use App\Shared\Infrastructure\Audit\CorrelationIdHolder;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;

/**
 * Adds correlation ID stamp to outgoing messages.
 *
 * When a message is dispatched during an HTTP request, this middleware
 * captures the current correlation ID and attaches it as a stamp.
 * The receiving worker will then use this stamp to restore the correlation ID.
 *
 * @see Story 1.7 - T3: Correlation ID
 */
final readonly class AddCorrelationIdStampMiddleware implements MiddlewareInterface
{
    public function handle(Envelope $envelope, StackInterface $stack): Envelope
    {
        // Only add stamp if not already present and we have a correlation ID
        if ($envelope->last(CorrelationIdStamp::class) === null) {
            $correlationId = CorrelationIdHolder::get();
            if ($correlationId !== null) {
                $envelope = $envelope->with(new CorrelationIdStamp($correlationId->value()));
            }
        }

        return $stack->next()->handle($envelope, $stack);
    }
}
