<?php

namespace Mtc\Plugins\Agent\Http\Middlewares;

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

class AgentAnonymous
{
    public const COOKIE_NAME = 'agent_guest_id';
    public const COOKIE_TTL_MINUTES = 60 * 24 * 30;

    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check()) {
            return $next($request);
        }

        $guestId = $request->cookie(self::COOKIE_NAME);

        if (!is_string($guestId) || !Str::isUuid($guestId)) {
            $guestId = (string) Str::uuid();
            Cookie::queue(
                self::COOKIE_NAME,
                $guestId,
                self::COOKIE_TTL_MINUTES,
                '/',
                null,
                $request->secure(),
                true,
                false,
                'lax'
            );
        }

        Auth::setUser(new ChatGuestUser([
            'id' => $guestId,
            'name' => 'Guest',
        ]));

        return $next($request);
    }
}
