<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RedirectBrowserToHomepage
{
    /**
     * Handle an incoming request.
     *
     * Redirects browser requests to the homepage while allowing API requests to proceed.
     * API requests are identified by the presence of:
     * - Accept: application/json header
     * - Authorization header (Bearer token)
     * - X-Requested-With: XMLHttpRequest header (AJAX)
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if this is an API request
        $isApiRequest = $request->expectsJson() ||
                       $request->hasHeader('Authorization') ||
                       $request->hasHeader('X-Requested-With');

        // If it's a browser request (not an API request), redirect to homepage
        if (! $isApiRequest) {
            return redirect('/');
        }

        return $next($request);
    }
}

