<?php

namespace App\Http\Requests\Security;

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

class IpBanRequest 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'],
            'hours' => ['nullable', 'integer', 'min:1', 'max:720'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $id = $this->input('id');
            $ip = $this->input('ip');
            if (!$id && !$ip) {
                $validator->errors()->add('id', 'Either id or ip is required.');
            }
        });
    }
}
