<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        // Check session-based authentication
        if (Auth::guard($guard)->check()) {
            return redirect()->route('dashboard');
        }

        // Check JWT authentication (since tokens are in localStorage, check cookies/headers)
        try {
            $token =
                $this->getBearerToken($request) ??
                $request->get('token') ??
                $request->cookie('access_token') ??
                $request->cookie('user-token');

            if ($token) {
                try {
                    JWTAuth::setToken($token);
                    $user = JWTAuth::authenticate();
                    if ($user) {
                        return redirect()->route('dashboard');
                    }
                } catch (\Exception $e) {
                    // Token invalid, continue
                }
            }
        } catch (\Exception $e) {
            // JWT check failed, continue
        }

        return $next($request);
    }

    /**
     * Extract Bearer token from Authorization header
     */
    private function getBearerToken(Request $request): ?string
    {
        if (!$request->hasHeader('Authorization')) {
            return null;
        }

        return preg_match('/Bearer\s+(.*)$/i', $request->header('Authorization'), $matches)
            ? $matches[1]
            : null;
    }
}
