<?php

namespace Lucent\Schema\Ui;

use Lucent\Schema\FieldInfo;
use Lucent\Schema\FieldInterface;
use Lucent\Schema\FieldType;
use Lucent\Schema\Nullable;
use Lucent\Schema\Validator\RequiredInterface;

class Block implements FieldInterface, RequiredInterface
{
    public FieldInfo $info;

    public function __construct(
        public string $name,
        public string $label,
        public bool   $nullable = false,
        public bool   $required = false,
        public string $default = "",
        public string $help = "",
        public bool   $readonly = false,
        public string $schema = "",
        public string $group = "",
    )
    {
        $this->info = new FieldInfo("block", "Block editor", FieldType::JSON);
    }

    public function format(array $input, array $output): array
    {
        $value = $input[$this->name] ?? null;

        if (is_string($value)) {
            $value = json_decode($value, true);
        }

        $output[$this->name] = (new Nullable($this->nullable, $value, []))->value();
        return $output;
    }

    public function failRequired(mixed $value): bool
    {
        return empty($value);
    }
}
