<?php

declare(strict_types=1);

namespace Maestro\Core\Http\Requests\Superadmin;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
use Maestro\Core\DataTables\DataTableColumnCatalog;

final class UpdateDataTableColumnDefaultsRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    /**
     * @return array<string, array<int, string>>
     */
    public function rules(): array
    {
        return [
            'visibleKeys' => ['required', 'array', 'min:1'],
            'visibleKeys.*' => ['required', 'string', 'max:128'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            $resourceKey = (string) $this->route('resourceKey', '');
            if ($resourceKey === '') {
                return;
            }

            $catalog = app(DataTableColumnCatalog::class);
            if (! $catalog->exists($resourceKey)) {
                $validator->errors()->add('visibleKeys', 'Unknown resource key.');

                return;
            }

            $allowed = [];
            foreach ($catalog->definitions($resourceKey) as $def) {
                $k = $def['key'] ?? null;
                if ($k !== null) {
                    $allowed[$k] = true;
                }
            }

            $keys = $this->input('visibleKeys', []);
            if (! is_array($keys)) {
                return;
            }

            foreach ($keys as $k) {
                if (! is_string($k) || ! isset($allowed[$k])) {
                    $validator->errors()->add('visibleKeys', 'Invalid column key: '.(is_string($k) ? $k : ''));

                    return;
                }
            }
        });
    }
}
