<?php

namespace Src\Modules\Auth\Laravel;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Providers\AppServiceProvider;
use Illuminate\Auth\SessionGuard;

class UsersProviderMiddleware
{

    public function handle(Request $request, Closure $next, ...$guards)
    {
        Auth::provider('user-provider', function ($app) {
            /** @var IModulesProvider */
            $modulesProvider = $app->make(AppServiceProvider::ADMIN_MODULES);
            return $modulesProvider->getAuthFactory()->getLaravelFactory()->getUserProvider();
        });

        Auth::extend('customSession', function ($app, $name, array $config) {
            $provider = Auth::createUserProvider($config['provider']);
            $session = $app['session.store'];
            $request = $app['request'];
            $cookie = $app['cookie'];

            $g = new SessionGuard('admins', $provider, $session, $request);
            $g->setCookieJar($cookie);

            return $g;
        });

        return $next($request);
    }
}
