<?php

namespace App\Providers;

use App\Models\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

// Conditionally load Telescope classes only if available
if (class_exists('Laravel\Telescope\TelescopeApplicationServiceProvider')) {
    class BaseTelescopeProvider extends \Laravel\Telescope\TelescopeApplicationServiceProvider {}
} else {
    class BaseTelescopeProvider extends ServiceProvider {
        public function register() {}
        public function boot() {}
    }
}

class TelescopeServiceProvider extends BaseTelescopeProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        // Only configure Telescope if it's available
        if (class_exists('Laravel\Telescope\Telescope')) {
            $this->hideSensitiveRequestDetails();

            // Filter data collection based on environment and authentication
            \Laravel\Telescope\Telescope::filter(function ($entry) {
                // Always allow in local environment
                if (app()->isLocal()) {
                    return true;
                }
                
                // In production, allow for authenticated users only
                // This ensures the dashboard works when accessed by authorized users
                return auth()->check();
            });
        }
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        // Only call parent boot if Telescope is available
        if (class_exists('Laravel\Telescope\TelescopeApplicationServiceProvider')) {
            parent::boot();
        }
        
        $this->gate();
    }

    /**
     * Prevent sensitive request details from being logged by Telescope.
     */
    protected function hideSensitiveRequestDetails(): void
    {
        if (!class_exists('Laravel\Telescope\Telescope')) {
            return;
        }
        
        if ($this->app->environment('local')) {
            return;
        }

        \Laravel\Telescope\Telescope::hideRequestParameters(['_token']);

        \Laravel\Telescope\Telescope::hideRequestHeaders([
            'cookie',
            'x-csrf-token',
            'x-xsrf-token',
        ]);
    }

    /**
     * Register the Telescope gate.
     *
     * This gate determines who can access Telescope in non-local environments.
     */
    protected function gate(): void
    {
        Gate::define('viewTelescope', function ($user = null) {
            // If no user, deny access
            if (!$user) {
                return false;
            }

            // Allow specific admin users in production
            $allowedEmails = array_filter(explode(',', env('TELESCOPE_ALLOWED_EMAILS', 'admin@example.com')));

            return app()->isLocal() || in_array($user->email, $allowedEmails);
        });
    }
}
