<?php

namespace App\Http\Middleware;

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

class EnsureAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 🔥 Session prüfen
        if (Auth::check()) {
            return $next($request);
        }

        // 🔥 Optional: API Token Support (für später)
        if ($token = $request->bearerToken()) {

            $user = \App\Models\User::whereHas('tokens', function ($q) use ($token) {
                $q->where('token', hash('sha256', $token));
            })->first();

            if ($user) {
                Auth::login($user);
                $user->tokens()->where('token', hash('sha256', $token))->update(['last_used_at' => now()]);
                return $next($request);
            }
        }

        if ($request->expectsJson()) {
            return response()->json([
                'message' => 'Unauthenticated',
            ], 401);
        }

        return redirect()->route('login');
    }
}
