<?php

/**
 * 文件功能：聊天室登录验证中间件
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class ChatAuthenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (! Auth::check()) {
            if ($request->expectsJson()) {
                return response()->json(['message' => '未登录', 'status' => 'error'], 401);
            }

            return redirect()->route('home')->withErrors([
                'auth' => '请先输入昵称进入聊天室',
            ]);
        }

        return $next($request);
    }
}
