<?php

namespace App\Domains\Permission\Handler;

use Illuminate\Http\Request;
use App\Exceptions\AuthException;
use App\Domains\Permission\Services\PermissionService;

class AuthAdminCheckPermission
{
    public function handle($account, $request)
    {
        $alias = $request->route()[1]['as'];

        $alias = str_replace('api.', '', $alias);

        $permissions = app(PermissionService::class)->getPermissions()->pluck('name')->toArray();

        foreach ($permissions as $key => $value) {
            $permissions[$key] = str_replace('_', '.', $value);
        }

        if (in_array($alias, $permissions) && !$this->shouldPassThrough($request)) {
            if (!$account->can($alias)) {
                throw new AuthException('用户无访问权限', AuthException::PERMISSION_DENIED);
            }
        }
    }

    /**
     * 可以跳过验证的路由
     *
     * @param Request $request
     * @return void
     */
    protected function shouldPassThrough($request)
    {
        $exceptArr = (array)config('domain.permission.except');

        foreach ($exceptArr as $except) {
            if ($except !== '/') {
                $except = trim($except, '/');
            }

            if ($request->is($except)) {
                return true;
            }
        }

        return false;
    }
}
