<?php

declare(strict_types=1);

namespace Builder\Core\Foundation\Resources;

use Illuminate\Http\Request;

final class RecordAction
{
    private ?string $permission = null;

    private bool $confirm = false;

    private ?\Closure $visibleFor = null;

    public function __construct(
        public readonly string $key,
        private string|\Closure $label,
        private \Closure $handler,
    ) {}

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

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

        return $this;
    }

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

        return $this;
    }

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

        return $this;
    }

    public function confirm(bool $confirm = true): self
    {
        $this->confirm = $confirm;

        return $this;
    }

    public function visibleFor(\Closure $condition): self
    {
        $this->visibleFor = $condition;

        return $this;
    }

    public function isVisibleFor(mixed $record): bool
    {
        return $this->visibleFor === null || ($this->visibleFor)($record);
    }

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

    public function getPermission(): ?string
    {
        return $this->permission;
    }

    public function isConfirm(): bool
    {
        return $this->confirm;
    }

    public function execute(mixed $record, Request $request): void
    {
        ($this->handler)($record, $request);
    }

    /** @return array{key: string, label: string, confirm: bool} */
    public function toArray(): array
    {
        return [
            'key' => $this->key,
            'label' => $this->getLabel(),
            'confirm' => $this->confirm,
        ];
    }
}
