<?php

namespace App\Providers;

use App\Models\ProviderConnection;
use App\Models\Tenant;
use App\Models\User;
use App\Policies\ProviderConnectionPolicy;
use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        ProviderConnection::class => ProviderConnectionPolicy::class,
    ];

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

        $resolver = app(CapabilityResolver::class);

        $defineTenantCapability = function (string $capability) use ($resolver): void {
            Gate::define($capability, function (User $user, Tenant $tenant) use ($resolver, $capability): bool {
                return $resolver->can($user, $tenant, $capability);
            });
        };

        foreach ([
            Capabilities::PROVIDER_VIEW,
            Capabilities::PROVIDER_MANAGE,
            Capabilities::PROVIDER_RUN,
            Capabilities::TENANT_MEMBERSHIP_VIEW,
            Capabilities::TENANT_MEMBERSHIP_MANAGE,
            Capabilities::TENANT_ROLE_MAPPING_VIEW,
            Capabilities::TENANT_ROLE_MAPPING_MANAGE,
            Capabilities::AUDIT_VIEW,
            Capabilities::TENANT_VIEW,
            Capabilities::TENANT_MANAGE,
            Capabilities::TENANT_DELETE,
            Capabilities::TENANT_SYNC,
        ] as $capability) {
            $defineTenantCapability($capability);
        }
    }
}
