<?php declare(strict_types=1);

namespace App\Http\Requests\Api\V1\Captcha;

use App\Contracts\FormRequestDto;
use App\Dto\HttpUserData;
use App\Dto\Request\Api\V1\Captcha\VerificationInformationDto;
use App\Models\CaptchaToken;
use App\Repositories\CaptchaTokenRepository;
use Illuminate\Foundation\Http\FormRequest;

final class VerificationInformationRequest extends FormRequest implements FormRequestDto
{
    private readonly CaptchaToken $captchaToken;

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(CaptchaTokenRepository $captchaTokenRepository): bool
    {
        if (!$this->hasHeader('private-token')) {
            return false;
        }
        $captchaToken = $captchaTokenRepository->getCaptchaTokenByPrivateToken($this->header('private-token'));
        if (is_null($captchaToken)) {
            return false;
        }

        $this->captchaToken = $captchaToken;

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'user_agent' => ['nullable', 'string'],
        ];
    }

    public function getDto(): VerificationInformationDto
    {
        $httpUserData = new HttpUserData(
            $this->getClientIp(),
            $this->userAgent(),
            $this->header('referer')
        );

        return new VerificationInformationDto(
            captchaToken: $this->captchaToken,
            httpUserData: $httpUserData,
            userAgent: $this->input('user_agent', null),
        );
    }
}