<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Automation\Trigger\InvocationMatcher;

use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\CategoryUpdatedInvocation;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\Invocation;

class CategoryUpdatedMatcher extends DaoMatcher
{
    public function supports(Invocation $invocation): bool
    {
        return $invocation instanceof CategoryUpdatedInvocation;
    }

    protected function getExtraConditions(Invocation $invocation): array
    {
        if (!$invocation instanceof CategoryUpdatedInvocation) {
            return [];
        }

        // In case an automation exists to observe all categories - ensure that property is not set!
        $subConditions = [
            "JSON_UNQUOTE(JSON_EXTRACT(automation_trigger, '$.selectionType')) = 'all'"
        ];

        $conditions = [
            "JSON_UNQUOTE(JSON_EXTRACT(automation_trigger, \"$.type\")) = 'category'",
            "JSON_UNQUOTE(JSON_EXTRACT(automation_trigger, \"$.event\")) = 'category-updated'",
        ];

        if ($category = $invocation->getCategory()) {
            $subConditions[] = "(JSON_UNQUOTE(JSON_EXTRACT(automation_trigger, '$.selectionType')) = 'categories' AND JSON_SEARCH(automation_trigger, 'one', '{$category}', null, '$.category') is not null)";
        }

        if ($attributes = $invocation->getAttributes()) {
            foreach ($attributes as $attribute) {
                $subConditions[] = "(JSON_UNQUOTE(JSON_EXTRACT(automation_trigger, '$.selectionType')) = 'attributes' AND JSON_SEARCH(automation_trigger, 'one', '{$attribute}', null, '$.propertyId') is not null)";
            }
        }

        if (!empty($subConditions)) {
            $conditions[] = '(' . implode(' OR ', $subConditions) . ')';
        }

        return $conditions;
    }
}
