<?php

namespace App\Services\Auth;

class RegistrationCaptchaService
{
    public function generate(?int $length = null): string
    {
        $length = $length ?? random_int(4, 8);
        $characters = 'ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghjkmnopqrstuvwxyz0123456789';
        $captchaText = '';

        for ($i = 0; $i < $length; $i++) {
            $captchaText .= $characters[random_int(0, strlen($characters) - 1)];
        }

        session()->put('captcha_answer', $captchaText);

        return $captchaText;
    }

    public function verify(string $input): bool
    {
        $expected = (string) session()->get('captcha_answer', '');
        if ($expected === '') {
            return false;
        }

        return hash_equals($expected, $input);
    }

    public function clear(): void
    {
        session()->forget('captcha_answer');
    }
}
