<?php

namespace Lucent\Query\Operator;

use Lucent\Query\Filter\Argument;

class OperatorDetector
{
    public function __construct(
        public OperatorRegistry $operatorRegistry
    )
    {
    }

    public function detect(mixed $value, string $filter): Argument
    {
        $operator = $this->detectOperator($filter);
        $field = $this->detectField($filter, $operator->name);
        return new Argument(
            field: str_replace(".", "->", $field),
            operator: $operator,
            value: $value
        );
    }

    private function detectOperator(string $filter): Operator
    {
        $exploded = explode("_", $filter);
        $candidate = end($exploded);
        return $this->operatorRegistry->matchByName($candidate);
    }

    private function detectField(string $filter, string $operator): string
    {
        $exploded = explode("_", $filter);
        $candidate = array_pop($exploded);
        if ($candidate === $operator) {
            return implode("_", $exploded);
        }
        return $filter;
    }
}