<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthCheckMiddleware
{
    /**
     * 处理传入请求
     *
     * @param Request $request
     * @param Closure $next
     * @param string|null $guard 认证守卫名称（默认为 api）
     * @param string|null $permission 需要检查的权限编码（可选）
     * @return Response
     */
    public function handle(Request $request, Closure $next, ?string $guard = 'api', ?string $permission = null): Response
    {
        // 检查是否已认证
        if (!auth($guard)->check()) {
            return response()->json([
                'code' => 401,
                'message' => '未登录或token已过期',
                'data' => null,
            ], 401);
        }

        // 获取当前用户
        $user = auth($guard)->user();

        // 检查用户状态
        if (isset($user->status) && $user->status !== 1) {
            return response()->json([
                'code' => 403,
                'message' => '账号已被禁用',
                'data' => null,
            ], 403);
        }

        // 如果需要检查权限
        if ($permission !== null) {
            if (!$this->checkPermission($user, $permission, $guard)) {
                return response()->json([
                    'code' => 403,
                    'message' => '无权限访问',
                    'data' => null,
                ], 403);
            }
        }

        // 将用户信息添加到请求中
        $request->merge(['auth_user' => $user]);

        // 更新用户最后活跃时间
        if (method_exists($user, 'updateLastActiveAt')) {
            $user->updateLastActiveAt();
        }

        return $next($request);
    }

    /**
     * 检查用户权限
     *
     * @param mixed $user
     * @param string $permission 权限编码
     * @param string $guard 认证守卫
     * @return bool
     */
    protected function checkPermission($user, string $permission, string $guard): bool
    {
        // 如果用户有所有权限标识
        if (method_exists($user, 'hasAllPermissions') && $user->hasAllPermissions()) {
            return true;
        }

        // 检查用户是否有指定权限
        if (method_exists($user, 'hasPermission')) {
            return $user->hasPermission($permission);
        }

        return false;
    }

    /**
     * 检查多个权限（满足任意一个即可）
     *
     * @param array $permissions 权限编码数组
     * @return bool
     */
    protected function checkAnyPermission($user, array $permissions): bool
    {
        foreach ($permissions as $permission) {
            if ($this->checkPermission($user, $permission, 'api')) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查多个权限（必须全部满足）
     *
     * @param array $permissions 权限编码数组
     * @return bool
     */
    protected function checkAllPermissions($user, array $permissions): bool
    {
        foreach ($permissions as $permission) {
            if (!$this->checkPermission($user, $permission, 'api')) {
                return false;
            }
        }
        return true;
    }
}
