<?php

declare(strict_types=1);

namespace App\Shared\Infrastructure\Monitoring;

use App\Shared\Infrastructure\Audit\CorrelationIdHolder;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;

/**
 * Monolog processor that adds correlation_id and tenant_id to all log entries.
 *
 * Enables distributed tracing by ensuring every log entry can be correlated
 * with its originating request, even across async boundaries.
 *
 * @see Story 1.8 - T5.2: Processor to add correlation_id automatically
 * @see Story 1.8 - T5.3: Processor to add tenant_id automatically
 */
final readonly class CorrelationIdLogProcessor implements ProcessorInterface
{
    public function __construct(
        private TenantContext $tenantContext,
    ) {
    }

    public function __invoke(LogRecord $record): LogRecord
    {
        $extra = $record->extra;

        // Add correlation ID for distributed tracing
        $correlationId = CorrelationIdHolder::get();
        if ($correlationId !== null) {
            $extra['correlation_id'] = $correlationId->value();
        }

        // Add tenant ID for multi-tenant filtering (use subdomain for consistency with Prometheus metrics)
        if ($this->tenantContext->hasTenant()) {
            $extra['tenant_id'] = $this->tenantContext->getCurrentTenantConfig()->subdomain;
        }

        return $record->with(extra: $extra);
    }
}
