<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Log\Processor;

if (!defined('_PS_VERSION_')) {
    exit;
}

/**
 * @internal
 */
final class UsedContextFieldsRemovingProcessor
{
    /**
     * @var callable
     */
    private $processor;

    /**
     * @param callable $processor
     */
    public function __construct(callable $processor)
    {
        $this->processor = $processor;
    }

    public function __invoke(array $record): array
    {
        if (false === strpos($record['message'], '{')) {
            return ($this->processor)($record);
        }

        $toRemove = [];

        foreach ($record['context'] as $key => $val) {
            $placeholder = '{' . $key . '}';
            if (false === strpos($record['message'], $placeholder)) {
                continue;
            }

            $toRemove[] = $key;
        }

        $record = ($this->processor)($record);

        foreach ($toRemove as $key) {
            unset($record['context'][$key]);
        }

        return $record;
    }
}
