<?php

declare(strict_types=1);

namespace Builder\Core\Http\Requests\Settings;

use Builder\Core\Foundation\Registry;
use Builder\Core\Foundation\Settings\SettingsDefinition;
use Illuminate\Foundation\Http\FormRequest;

final class UpdateSettingsRequest extends FormRequest
{
    public function authorize(): bool
    {
        $definition = $this->resolveDefinition();

        if ($definition === null) {
            abort(404);
        }

        $permission = $definition->getPage()->getPermission();

        if ($permission === null) {
            return true;
        }

        return (bool) auth()->user()?->can($permission);
    }

    /** @return array<string, mixed> */
    public function rules(): array
    {
        /** @var SettingsDefinition $definition Guaranteed non-null: authorize() aborts 404 first. */
        $definition = $this->resolveDefinition();

        return $definition->getRules() ?: [];
    }

    private function resolveDefinition(): ?SettingsDefinition
    {
        $registry = app(Registry::class);
        $page = (string) $this->route('page');
        $parent = $this->route('parent') !== null ? (string) $this->route('parent') : null;
        $key = $parent !== null ? "{$parent}.{$page}" : $page;

        return $registry->resolveSettingsPage($key);
    }
}
