<?php

namespace Openguru\OpenCartFramework\CriteriaBuilder;

use InvalidArgumentException;
use Openguru\OpenCartFramework\Support\Utils;

class RulesRegistry
{
    private array $items = [];

    public function getRuleId(string $class): string
    {
        $segments = explode('\\', $class);
        $lastSegment = end($segments);
        if (! $lastSegment) {
            throw new InvalidArgumentException("Class {$class} does not exist");
        }

        return 'RULE_' . implode('_', array_map('mb_strtoupper', Utils::ucsplit($lastSegment)));
    }

    public function has(string $ruleId): bool
    {
        return array_key_exists($ruleId, $this->items);
    }

    /**
     * @param string|array $ruleId
     * @param string|null $class
     * @return void
     */
    public function register($ruleId, string $class = null): void
    {
        if (is_array($ruleId)) {
            foreach ($ruleId as $key => $value) {
                $this->register($key, $value);
            }

            return;
        }

        if ($this->has($ruleId)) {
            throw new InvalidArgumentException("Rule '$ruleId' is already registered");
        }

        $this->items[$ruleId] = $class;
    }

    public function get(string $ruleId)
    {
        if (! $this->has($ruleId)) {
            throw new InvalidArgumentException("Rule '$ruleId' is not registered");
        }

        return $this->items[$ruleId];
    }

    public function getItems(): array
    {
        return $this->items;
    }
}
