<?php

namespace App\Http\Middleware;

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

class EmployerApiMiddleware
{
    /**
     * 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);
        $user = User::where('api_token', $token)->where('role', 'employer')->first();

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

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

        return $next($request);
    }
}
