<?php

namespace App\Providers;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Telescope\Contracts\PrunableRepository;
use Laravel\Telescope\Telescope;

/**
 * Class TelescopeServiceProvider
 *
 * @package App\Providers
 */
class TelescopeServiceProvider extends ServiceProvider
{
    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        // Skip if not installed (e.g production server)
        if (class_exists(Telescope::class) === false) {
            return;
        }

        $this->authorize();
        $this->registerPruning();
    }

    /**
     * Register Telescope authorization
     */
    protected function authorize()
    {
        Gate::define('viewTelescope', function ($user) {
            return $user->hasRole('mtc');
        });

        Telescope::auth(function ($request) {
            return app()->environment('local') || Gate::check('viewTelescope', [$request->user()]);
        });
    }

    /**
     * Work around staging environment not having cron scheduling
     * Telescope will automatically prune once per day or on cache clear
     */
    protected function registerPruning()
    {
        // Skip doing this in local
        if ($this->app->environment('local') === true) {
            return;
        }

        Cache::remember('telescope-prune', now()->addDay(), function () {
            try {
                $this->app->make(PrunableRepository::class)
                    ->prune(now()->subDays(config('telescope.prune_days')));
            } catch (\Exception $exception) {
                // Fail silently
            }
            return true;
        });
    }
}
