<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
use Closure;
use Illuminate\Support\Facades\Auth;



class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request): ?string
    {
        return $request->expectsJson() ? null : route('login');
    }

    public function handle($request, Closure $next, ...$guards)
    {
        if (!auth('sanctum')->check()) {
            if($request->expectsJson()){
                return response()->json('',401);
            }else{
                return redirect(route('login'));
            }
        }else{
            if(!$request->header('Accept-Language')){
                $acceptLanguage = $request->header('Accept-Language');
                app()->setLocale($acceptLanguage);
            }

            if (!Auth::guard('sanctum')->check()) {
                $request->merge(['user' => null]);
            } else {
                $request->merge(['user' => Auth::guard('sanctum')->user()]);
            }
        }

        return $next($request);
    }
}
