<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class SetAuditSessionVariables
{
    public function handle(Request $request, Closure $next): Response
    {
        // 요청 단위 operation_id (인증 여부와 무관하게 항상 설정)
        DB::statement('SET @sam_operation_id = ?', [Str::uuid()->toString()]);

        if (auth()->check()) {
            DB::statement('SET @sam_actor_id = ?', [auth()->id()]);
            DB::statement('SET @sam_session_info = ?', [
                json_encode([
                    'ip' => $request->ip(),
                    'ua' => mb_substr((string) $request->userAgent(), 0, 255),
                    'route' => $request->route()?->getName(),
                ], JSON_UNESCAPED_UNICODE),
            ]);
        }

        return $next($request);
    }
}
