<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Laravel\Cashier\Cashier;
use GuzzleHttp\Client as HttpClient;
use App\MicroApi\Services\UserService;
use Illuminate\Support\Facades\Auth;
use App\Services\Auth\MicroUserProvider;
use App\Services\Auth\JwtGuard;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Cashier::useCurrency(config('cart.currency'), config('cart.currency_symbol'));
        // 扩展 User Provider
        Auth::provider('micro', function($app, array $config) {
            // 返回一个Illuminate\Contracts\Auth\UserProvider实例...
            return new MicroUserProvider($config['model']);
        });

        // 扩展 Auth Guard
        Auth::extend('jwt', function($app, $name, array $config) {
            // 返回一个Illuminate\Contracts\Auth\Guard实例...
            return new JwtGuard(Auth::createUserProvider($config['provider']), $app->make('request'));
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // 以单例模式绑定 HttpClient 实例到 App 容器
        $this->app->singleton('HttpClient', function ($app) {
            return new HttpClient([
                'base_uri' => config('services.micro.api_gateway'),
                'timeout'  => config('services.micro.timeout'),
                'headers'  => [
                    'Content-Type' => 'application/json'
                ]
            ]);
        });
        // 以单例模式绑定用户服务到服务容器
        $this->app->singleton('microUserService', function ($app) {
            return new UserService();
        });
    }
}
