<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Symfony\Component\HttpFoundation\Response;

/**
 * Same behavior as Laravel's RedirectIfAuthenticated, but returns JSON when the
 * client expects JSON (e.g. modal AJAX login) instead of a 302 that jQuery follows
 * into HTML with no feedback.
 */
class RedirectIfAuthenticatedWithJsonResponse
{
    public function handle(Request $request, Closure $next, string ...$guards): Response
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
                if ($request->expectsJson() || $request->ajax()) {
                    return response()->json([
                        'success' => true,
                        'already_authenticated' => true,
                        'redirect_url' => $this->redirectTarget(),
                        'message' => __('already_signed_in_redirecting'),
                    ]);
                }

                return redirect($this->redirectTarget());
            }
        }

        return $next($request);
    }

    protected function redirectTarget(): string
    {
        foreach (['admin.dashboard', 'dashboard', 'home'] as $named) {
            if (Route::has($named)) {
                return route($named);
            }
        }

        $routes = Route::getRoutes()->get('GET');
        foreach (['dashboard', 'home'] as $uri) {
            if (isset($routes[$uri])) {
                return '/'.$uri;
            }
        }

        return '/';
    }
}
