<?php

namespace Mtc\Plugins\Agent\Http\Middlewares;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Mtc\Plugins\Agent\Models\ChatGuestUser;
use Symfony\Component\HttpFoundation\Response;

class AgentAnonymous
{
    public function handle(Request $request, Closure $next): Response
    {
        // Check if the frontend sent a specific Guest ID
        $requestedGuestId = $request->header('X-Guest-ID');

        if ($requestedGuestId) {
            $guest = new ChatGuestUser([
                'id' => $requestedGuestId, // Use the ID from the frontend
                'name' => 'Guest',
            ]);

            Auth::setUser($guest);
        }
        // Fallback: If no header and not logged in (legacy logic)
        elseif (!Auth::check()) {
            // Note: This path will likely fail your channel auth check
            // because the UUID won't match the channel name.
            $guest = new ChatGuestUser([
                'id' => \Illuminate\Support\Str::uuid(),
                'name' => 'Guest',
            ]);
            Auth::setUser($guest);
        }

        return $next($request);
    }
}
