<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Services\ImpersonationService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

final class ImpersonationMiddleware
{
    public function __construct(
        private readonly ImpersonationService $impersonationService
    ) {}

    public function handle(Request $request, Closure $next): Response
    {
        // Check if impersonation has expired
        if ($this->impersonationService->isImpersonating() &&
            $this->impersonationService->isImpersonationExpired()) {

            $this->impersonationService->stopImpersonation($request);

            // Redirect to admin dashboard with expired message
            return redirect()->to(\Filament\Pages\Dashboard::getUrl())->with('impersonation_expired', 'Your impersonation session has expired.');
        }

        // Share impersonation data with all views
        if ($this->impersonationService->isImpersonating()) {
            $impersonator = $this->impersonationService->getCurrentImpersonator();
            $remainingMinutes = $this->impersonationService->getRemainingMinutes();
            $startTime = $this->impersonationService->getImpersonationStartTime();

            view()->share('isImpersonating', true);
            view()->share('impersonator', $impersonator);
            view()->share('impersonationTarget', Auth::user());
            view()->share('impersonationRemainingMinutes', $remainingMinutes);
            view()->share('impersonationStartTime', $startTime);
        } else {
            view()->share('isImpersonating', false);
            view()->share('impersonator', null);
            view()->share('impersonationTarget', null);
            view()->share('impersonationRemainingMinutes', 0);
            view()->share('impersonationStartTime', null);
        }

        return $next($request);
    }
}
