<?php

namespace App\Http\Requests\Admin;

use App\Models\AdminUser;
use App\Http\Requests\ApiFormRequest;
use App\Support\AdminSettingPolicy;

final class AdminSettingBatchUpdateRequest extends ApiFormRequest
{
    public function authorize(): bool
    {
        $admin = $this->lotteryAdmin();
        if (! $admin instanceof AdminUser) {
            return false;
        }

        /** @var list<array{key?: mixed}>|null $items */
        $items = $this->input('items');
        if (! is_array($items)) {
            return true;
        }

        foreach ($items as $item) {
            $key = is_array($item) ? (string) ($item['key'] ?? '') : '';
            if (! AdminSettingPolicy::canUpdate($admin, $key)) {
                return false;
            }
        }

        return true;
    }

    public function rules(): array
    {
        return [
            'items' => ['required', 'array', 'min:1', 'max:50'],
            'items.*.key' => ['required', 'string', 'max:128'],
            'items.*.value' => ['present'],
        ];
    }

    public function after(): array
    {
        return [
            function (): void {
                /** @var list<array{key: string, value: mixed}> $items */
                $items = $this->validated('items', []);
                AdminSettingPolicy::validateItems($items);
            },
        ];
    }
}
