<?php

namespace App\Providers;

use App\Models\User;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    public function boot(): void
    {
        $this->registerPolicies();

        // Fallback: map generic CRUD abilities to permission slugs directly
        foreach (['create', 'read', 'update', 'delete'] as $ability) {
            Gate::define($ability, function (User $user) use ($ability): bool {
                return $user->hasPermission($ability) || $user->hasRole('admin');
            });
        }

        // More specific examples
        Gate::define('manage-settings', function (User $user): bool {
            return $user->hasPermission('manage-settings') || $user->hasRole('admin');
        });
        Gate::define('manage-imports', function (User $user): bool {
            return $user->hasPermission('manage-imports') || $user->hasRole('admin');
        });
        Gate::define('manage-document-templates', function (User $user): bool {
            return $user->hasPermission('manage-document-templates') || $user->hasRole('admin');
        });

        // Global override for admin role
        Gate::before(function (User $user, string $ability) {
            if ($user->hasRole('admin')) {
                return true;
            }

            return null; // fall through
        });
    }
}
