<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Automation\Action\ExecutionFactory;

use idoit\Module\SyneticsFlows\Automation\Action\ActionType\CmdbChange\CategoryChange;
use idoit\Module\SyneticsFlows\Automation\Action\ActionType\CmdbChange\CmdbChange;
use idoit\Module\SyneticsFlows\Template\Template;

class ProcessCategoryChanges
{
    /**
     * @param Template $template
     * @param CategoryChange[] $categoryChanges
     *
     * @return CategoryChange[]
     */
    public function process(Template $template, array $categoryChanges): array
    {
        if (empty($categoryChanges)) {
            return [];
        }

        $processedCategoryChanges = [];
        foreach ($categoryChanges as $categoryChange) {
            $processed = $this->processCategoryChange($categoryChange, $template);
            if ($processed) {
                $processedCategoryChanges[] = $processed;
            }
        }
        return $processedCategoryChanges;
    }

    private function processCategoryChange(CategoryChange $categoryChange, Template $template): ?CategoryChange
    {
        if (!defined($categoryChange->getCategoryId())) {
            return null;
        }
        $newChanges = [];

        foreach ($categoryChange->getChanges() as $change) {
            $value = $change->getValue();
            if (!is_string($value)) {
                $newChanges[] = $change;
                continue;
            }

            $newValue = $template->process($change->getValue());
            $newChanges[] = new CmdbChange($change->getAttribute(), $newValue);
        }
        return new CategoryChange(
            $categoryChange->getCategoryId(),
            $newChanges,
        );
    }
}