<?php

namespace App\Services\Auth;

class RegistrationCaptchaService
{
    private function cacheKey(): string
    {
        $ip = (string) (request()?->ip() ?? 'unknown');
        $ua = (string) (request()?->header('User-Agent') ?? '');
        $hash = substr(sha1($ua), 0, 12);
        return 'captcha:' . $ip . ':' . $hash;
    }

    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)];
        }

        cache()->put($this->cacheKey(), $captchaText, now()->addMinutes(10));

        return $captchaText;
    }

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

        return hash_equals($expected, $input);
    }

    public function clear(): void
    {
        cache()->forget($this->cacheKey());
    }
}
