<?php

namespace App\Providers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Event::listen(function (\SocialiteProviders\Manager\SocialiteWasCalled $event) {
            $event->extendSocialite('keycloak', \SocialiteProviders\Keycloak\Provider::class);
        });

        Blade::if('permission', function ($permission) {
            return Auth::check() && Auth::user()->hasPermission($permission);
        });

        Blade::if('role', function ($role) {
            return Auth::check() && Auth::user()->hasRole($role);
        });

        Blade::if('anyrole', function (...$roles) {
            return Auth::check() && Auth::user()->hasAnyRole($roles);
        });

        Blade::if('allpermissions', function (...$permissions) {
            if (!Auth::check()) {
                return false;
            }

            foreach ($permissions as $permission) {
                if (!Auth::user()->hasPermission($permission)) {
                    return false;
                }
            }

            return true;
        });

        Blade::if('anypermission', function (...$permissions) {
            if (!Auth::check()) {
                return false;
            }

            foreach ($permissions as $permission) {
                if (Auth::user()->hasPermission($permission)) {
                    return true;
                }
            }

            return false;
        });

        DB::listen(function ($query) {
            Log::info(
                $query->sql,
                [
                    'bindings' => $query->bindings,
                    'time' => $query->time,
                ]
            );
        });
    }
}
