<?php

namespace App\Http\Middleware;

use App\Models\Worker;
use Closure;
use Illuminate\Http\Request;

class WorkerApiMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $authHeader = $request->header('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return response()->json([
                'success' => false,
                'message' => 'Authentication token required.'
            ], 401);
        }

        $token = substr($authHeader, 7);
        $worker = Worker::where('api_token', $token)->first();

        if (!$worker) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid or expired authentication token.'
            ], 401);
        }

        // Attach worker object to request attributes so controllers can read it using $request->attributes->get('worker')
        $request->attributes->set('worker', $worker);

        return $next($request);
    }
}
