<?php

namespace App\Services;

use App\Models\EarnApiAccessLog;
use App\Models\EarnApiToken;
use Illuminate\Http\Request;

class EarnApiAccessLogger
{
    public function record(Request $request, string $event, int $status, ?string $failureCode = null, ?EarnApiToken $token = null, ?string $deviceHash = null, ?string $devicePreview = null): void
    {
        $token ??= $request->attributes->get('earn_api_token');
        $userAgent = preg_replace('/[\x00-\x1F\x7F]+/u', ' ', (string) $request->userAgent());
        EarnApiAccessLog::query()->create([
            'earn_member_id' => $token?->tokenable_id, 'personal_access_token_id' => $token?->id,
            'token_preview' => $token?->token_hint, 'event' => $event,
            'device_id_hash' => $deviceHash, 'device_id_preview' => $devicePreview,
            'ip_address' => $request->ip(), 'user_agent' => mb_substr((string) $userAgent, 0, 255),
            'http_method' => $request->method(), 'route_name' => $request->route()?->getName(),
            'response_status' => $status, 'failure_code' => $failureCode,
            'occurred_at' => now(), 'created_at' => now(),
        ]);
    }
}
