<?php

namespace App\Http\Middleware;

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


class HandleApiAuthentication extends Middleware
{
    /**
     * Handle an unauthenticated request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  array  $guards
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     */
    protected function unauthenticated($request, array $guards)
    {
        // If the request expects JSON (which all API calls should),
        // return a JSON error response instead of a redirect.
        if ($request->expectsJson()) {
            return response()->json(['message' => 'Unauthenticated.'], 401);
        }

        // For any non-JSON request, we can still redirect to a login route
        // if you have one, or just return a 401 error.
        // For a pure API, you might just throw an AuthorizationException.
        return parent::unauthenticated($request, $guards);
    }
}