<?php

declare(strict_types=1);

namespace App\Providers;

use App\Models\User;
use Illuminate\Support\Facades\Gate;
use Laravel\Horizon\Horizon;
use Laravel\Horizon\HorizonApplicationServiceProvider;

class HorizonServiceProvider extends HorizonApplicationServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        parent::boot();

        $slack = config('services.slack.webhook_url');
        if (! empty($slack)) {
            Horizon::routeSlackNotificationsTo($slack, '#ops-alerts');
        }
    }

    /**
     * Register the Horizon gate.
     *
     * Production: super_admin role only. Local: allow any authenticated user.
     */
    protected function gate(): void
    {
        Gate::define('viewHorizon', function (?User $user = null) {
            if (! $user) {
                return false;
            }

            if (app()->environment('local')) {
                return true;
            }

            return method_exists($user, 'hasRole') && $user->hasRole('super_admin');
        });
    }
}
