<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class ApiTokenAuth
{
    public function handle(Request $request, Closure $next)
    {
        $header = $request->header('Authorization', '');
        if (! str_starts_with($header, 'Bearer ')) {
            return response()->json(['error' => ['code' => 'unauthorized']], 401);
        }
        $token = substr($header, 7);
        $userId = Cache::get('api_token:'.$token);
        if (! $userId) {
            return response()->json(['error' => ['code' => 'unauthorized']], 401);
        }
        $user = User::find($userId);
        if (! $user) {
            return response()->json(['error' => ['code' => 'unauthorized']], 401);
        }
        Auth::login($user); // for policies if needed
        return $next($request);
    }
}

