<?php

namespace App\Providers;

use App\Models\Feature;
use App\Models\Inspection;
use App\Models\Issue;
use App\Models\Project;
use App\Models\Task;
use App\Observers\FeatureObserver;
use App\Observers\InspectionObserver;
use App\Observers\IssueObserver;
use App\Policies\TaskPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        // Register route model bindings early (before routes are loaded)
        Route::model('project', Project::class);
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        // Register model observers for cache invalidation
        Feature::observe(FeatureObserver::class);
        Inspection::observe(InspectionObserver::class);
        Issue::observe(IssueObserver::class);

        // Re-register model bindings so they persist in route cache
        Route::model('project', Project::class);

        // Register policies
        Gate::policy(Task::class, TaskPolicy::class);

        // Super-admin bypass: anyone with the "manage all" permission
        // (the Admin role has it) passes every authorization check.
        // Return true to allow, or null to let normal checks run — never false.
        Gate::before(function ($user, $ability) {
            try {
                return $user->hasPermissionTo('manage all') ? true : null;
            } catch (\Throwable $e) {
                return null;
            }
        });
    }
}
