<?php

namespace App\Http\Requests\Security;

use App\Http\Requests\ApiFormRequest;
use Illuminate\Contracts\Validation\Validator;

class IpUnbanRequest extends ApiFormRequest
{
    public function authorize(): bool
    {
        return $this->user() !== null || auth()->user() !== null;
    }

    public function rules(): array
    {
        return [
            'id' => ['nullable', 'integer', 'min:1'],
            'ip' => ['nullable', 'ip'],
            'all' => ['nullable', 'boolean'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $id = $this->input('id');
            $ip = $this->input('ip');
            $all = filter_var($this->input('all'), FILTER_VALIDATE_BOOLEAN);

            if (!$all && !$id && !$ip) {
                $validator->errors()->add('id', 'Either id, ip, or all=true is required.');
            }
        });
    }
}
