<?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;
use function is_bool;

class Checkbox implements FieldInterface, RequiredInterface
{

    public FieldInfo $info;

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

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

        if (is_bool($value)) {
            $newValue = $value;
        } else {
            $newValue = (new Nullable($this->nullable, $value, false))->value();
        }
        $output[$this->name] = $newValue;
        return $output;
    }

    public function failRequired(mixed $value): bool
    {
        return (bool)$value !== true;
    }
}

