<?php

use App\Modules\BaseAuth\Models\AuthEvent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

/**
 * Store auth event
 */
function storeAuthEvent(string $name, Request $request): void
{
    try {
        AuthEvent::create([
            'name' => $name,
            'request_method' => $request->method(),
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'target_url' => $request->url(),
            'options' => json_encode($request->all()),
        ]);

        Config::set('logging.channels.auth_activity', [
            'driver' => 'single',
            'path' => storage_path('logs/auth_activity.log'),
            'level' => 'debug',
        ]);

        Log::channel('auth_activity')
            ->{AuthEvent::logType($name)}(sprintf(
                '%s, APP_NAME: %s, REQUEST_TYPE: %s, SOURCE_IP: %s, SOURCE_PORT: %s, SOURCE_URL: %s, DESTINATION_IP: %s, DESTINATION_PORT: %s, DESTINATION_COUNTRY: %s, USER_ID: %s',
                $name,
                config()->string('app.name'),
                $request->method(),
                $request->ip(),
                $_SERVER['REMOTE_PORT'], // @phpstan-ignore-line
                $request->url(),
                $request->host(),
                $request->getPort(),
                (module('IpStack')->isEnabled()) ? getCountryCodeFromIp($request->ip()) : 'TM',
                $request->user()->id ?? '-',
            ));
    } catch (Exception $e) {
        Log::error('could-not-store-auth-event', [
            'message' => $e->getMessage(),
        ]);
    }
}
