<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Base;
use Illuminate\Http\Request;

class HtmxAwareAuthenticate extends Base
{
    protected function redirectTo(Request $request): ?string
    {
        // Non-HTMX: fall back to normal redirect
        return $request->isMethod('get') ? route('login') : null;
    }

    protected function unauthenticated($request, array $guards)
    {
        // If it was an HTMX request, send 401 + HX-Redirect instead of 302
        if ($request->header('HX-Request')) {
            abort(
                response('')
                    ->header('HX-Redirect', route('login'))
                    ->setStatusCode(401)
            );
        }

        parent::unauthenticated($request, $guards);
    }
}
