<?php

namespace Lucent\Query\BuilderConverter;

use Illuminate\Database\Query\Builder;
use Lucent\Query\Filter\Argument;

readonly class InNum implements IBuilderConverter
{

    public function __construct(private Argument $argument)
    {
    }

    public function toAndQueryBuilder(Builder $builder): Builder
    {
        return $builder->whereIn($this->argument->field, $this->formatValue());
    }

    public function toOrQueryBuilder(Builder $builder): Builder
    {
        return $builder->orWhereIn($this->argument->field, $this->formatValue());
    }

    private function formatValue(): array
    {
        $value = $this->argument->value;
        if (is_string($value)) {
            $value = explode(",", $value);
        }
        return array_map(fn($v) => $this->formatNumber($v), $value);
    }

    private function formatNumber(string $value): float|int
    {
        $value = trim($value);
        return str_contains($value, ".") ? floatval($value) : intval($value);
    }
}