<?php

namespace Lucent\Schema\Ui;

use Illuminate\Support\Str;
use Lucent\Schema\FieldInfo;
use Lucent\Schema\FieldInterface;
use Lucent\Schema\FieldType;
use Lucent\Schema\Nullable;
use Lucent\Schema\Validator\RequiredInterface;

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

    public function __construct(
        public string $name,
        public string $label,
        public bool   $required = false,
        public bool   $nullable = false,
        public ?int   $min = null,
        public ?int   $max = null,
        public string $default = "",
        public string $help = "",
        public bool   $readonly = false,
        public string $source = "",
        public string $group = "",
    )
    {
        $this->info = new FieldInfo("slug", "Slug", FieldType::STRING);
    }

    public function format(array $input, array $output): array
    {
        $value = !empty($input[$this->name]) ? (string)$input[$this->name] : null;
        if(empty($value)){
            $value = Str::slug($input[$this->source]);
        }

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


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

