<?php

declare(strict_types=1);

namespace App\Configs;

use Illuminate\Support\Arr;
use Laravel\Nova\Fields\Markdown;

/**
 * Config Field class for the "content" config group.
 * Defines fields, defaults, and Nova fields for content settings.
 */
final class Content
{
    public string $title = 'Content';

    public string $description = 'Content settings';

    public string $key = 'content';

    /**
     * Returns the field definitions with their type and default value for this config group.
     */
    public function getFieldKeys(): array
    {
        return [
            'disclaimer' => [
                'type' => 'markdown',
                'default' => '',
            ],
        ];
    }

    /**
     * Returns the default value for the given field key, or null if the key does not exist.
     */
    public function getDefault(string $key): mixed
    {
        $fields = $this->getFieldKeys();

        if (! Arr::has($fields, $key)) {
            return null;
        }

        return Arr::get($fields, "{$key}.default");
    }

    /**
     * Returns Nova field instances for this config group, each wired with
     * resolveUsing (read from json_value with default fallback) and
     * fillUsing (write back into json_value) callbacks.
     */
    public function getNovaFields(): array
    {
        return [
            Markdown::make('Disclaimer', 'disclaimer')
                ->resolveUsing(function (mixed $value, mixed $resource): string {
                    $jsonValue = Arr::get((array) $resource->json_value, 'disclaimer');

                    if ($jsonValue === null || $jsonValue === '') {
                        return (string) $this->getDefault('disclaimer');
                    }

                    return (string) $jsonValue;
                })
                ->fillUsing(function (mixed $request, mixed $model, string $attribute, string $requestAttribute): void {
                    $current = Arr::wrap((array) $model->json_value);
                    Arr::set($current, $attribute, $request->{$requestAttribute});
                    $model->json_value = $current;
                }),
        ];
    }
}
