<?php
namespace App\Domains\Auth\Providers;

use App\Exceptions\NotExistException;
use Illuminate\Support\ServiceProvider;
use App\Domains\Auth\Services\AuthService;
use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Contracts\Auth\Authenticatable;
use App\Domains\Auth\Providers\MiddlewareProvider;
use App\Domains\Auth\Providers\RouteServiceProvider;
use App\Domains\Account\Repositories\AccountRepository;
use App\Domains\Virtual\Repositories\CompanyAccountRepository;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * 引导启动任何应用程序服务
     *
     * php artisan make:migration --path=app/Domains/Auth/Database/migrations
     *
     * @return void
     */
    public function boot()
    {
        app(Gate::class)->before(function (Authenticatable $user, string $ability) {
            try {
                if (method_exists($user, 'hasPermissionTo')) {
                    return $user->hasPermissionTo($ability) ?: null;
                }
            } catch (NotExistException $e) {
            }
        });
    }

    /**
     * 注册一个服务提供者
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('auth:admin', function ($app) {
            return  new AuthService('admin', app(AccountRepository::class));
        });

        $this->app->singleton('auth:company', function ($app) {
            return  new AuthService('company', app(CompanyAccountRepository::class));
        });

        $this->app->register(RouteServiceProvider::class);
        $this->app->register(MiddlewareServiceProvider::class);
    }
}
