<?php

declare(strict_types=1);

namespace Builder\Core\Foundation\Tables;

use Closure;

final class Filter
{
    private string $label;

    private string $type = 'text';

    /** @var array<string, string>|Closure|null */
    private array|Closure|null $options = null;

    private ?Closure $apply = null;

    private function __construct(private readonly string $key)
    {
        $this->label = $key;
    }

    public static function make(string $key): self
    {
        return new self($key);
    }

    public function label(string $label): self
    {
        $this->label = $label;

        return $this;
    }

    public function type(string $type): self
    {
        $this->type = $type;

        return $this;
    }

    /** @param array<string, string>|Closure $options */
    public function options(array|Closure $options): self
    {
        $this->options = $options;

        return $this;
    }

    public function apply(Closure $apply): self
    {
        $this->apply = $apply;

        return $this;
    }

    public function getKey(): string
    {
        return $this->key;
    }

    public function getLabel(): string
    {
        return $this->label;
    }

    public function getType(): string
    {
        return $this->type;
    }

    /** @return array<string, string>|null */
    public function getOptions(): ?array
    {
        if ($this->options === null) {
            return null;
        }

        if ($this->options instanceof Closure) {
            return ($this->options)();
        }

        return $this->options;
    }

    public function getApply(): ?Closure
    {
        return $this->apply;
    }

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'key' => $this->key,
            'label' => $this->label,
            'type' => $this->type,
            'options' => $this->getOptions(),
        ];
    }
}
