<?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\CaptchaPublicToken;
use App\Models\CaptchaToken;
use App\Repositories\CaptchaTokenRepository;
use Illuminate\Foundation\Http\FormRequest;

final class CaptchaRequest 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('public-token')) {
            return false;
        }
        $captchaToken = $captchaTokenRepository->getCaptchaTokenByPublicToken($this->header('public-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 [

        ];
    }

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

        return new CaptchaPublicToken(
            $this->captchaToken,
            $httpUserData
        );
    }
}