<?php declare(strict_types=1);

namespace App\Services\CaptchaLog;

use App\Dto\HttpUserData;
use App\Enums\CaptchaLogType;
use App\Events\CreatedCaptchaLog;
use App\Models\Captcha;
use App\Models\CaptchaLog;
use Illuminate\Support\Str;

final readonly class CaptchaLogHandler
{
    public function handleStore(int $captchaId, CaptchaLogType $captchaLogType, HttpUserData $httpUserData): CaptchaLog
    {
        $userAgent = $httpUserData->getUserAgent();
        if (!is_null($userAgent)) {
            $userAgent = Str::limit($userAgent, 255, '');
        }

        $referer = $httpUserData->getReferer();
        if (!is_null($referer)) {
            $referer = Str::limit($referer, 10000, '');
        }

        $captchaLog = CaptchaLog::create([
            'captcha_id' => $captchaId,
            'type' => $captchaLogType,
            'ip' => $httpUserData->getClientIp(),
            'user_agent' => $userAgent,
            'referer' => $referer,
        ]);

        CreatedCaptchaLog::dispatch($captchaLog);

        return $captchaLog;
    }
}
