<?php

namespace Openguru\OpenCartFramework\CriteriaBuilder;

use InvalidArgumentException;
use Openguru\OpenCartFramework\CriteriaBuilder\Rules\BaseRule;
use Openguru\OpenCartFramework\QueryBuilder\Builder;

class CriteriaBuilder
{
    private RulesRegistry $rulesRegistry;

    public function __construct(RulesRegistry $rulesRegistry)
    {
        $this->rulesRegistry = $rulesRegistry;
    }

    public function apply(Builder $queryBuilder, array $query): void
    {
        $operand = $query['operand'] ?? 'AND';
        $rules = $query['rules'] ?? [];

        foreach ($rules as $ruleId => $rule) {
            if (! $this->rulesRegistry->has($ruleId)) {
                throw new InvalidArgumentException('Invalid rule: ' . $ruleId);
            }

            $className = $this->rulesRegistry->get($ruleId);

            $criteria = [];
            foreach ($rule['criteria'] as $name => $item) {
                $criteria[$name] = new Criterion($item['type'], $item['params']);
            }

            /** @var BaseRule $ruleClass */
            $ruleClass = new $className($ruleId, $criteria);
            $ruleClass->apply($queryBuilder, $operand);
        }
    }
}
