<?php

namespace App\Services\Auth;

use App\Support\Auth\Capabilities;
use App\Support\TenantRole;

/**
 * Role to Capability Mapping (Single Source of Truth)
 *
 * This class defines which capabilities each role has.
 * All capability strings MUST be references from the Capabilities registry.
 */
class RoleCapabilityMap
{
    private static array $roleCapabilities = [
        TenantRole::Owner->value => [
            Capabilities::TENANT_VIEW,
            Capabilities::TENANT_MANAGE,
            Capabilities::TENANT_DELETE,
            Capabilities::TENANT_SYNC,

            Capabilities::TENANT_MEMBERSHIP_VIEW,
            Capabilities::TENANT_MEMBERSHIP_MANAGE,

            Capabilities::TENANT_ROLE_MAPPING_VIEW,
            Capabilities::TENANT_ROLE_MAPPING_MANAGE,

            Capabilities::PROVIDER_VIEW,
            Capabilities::PROVIDER_MANAGE,
            Capabilities::PROVIDER_RUN,

            Capabilities::AUDIT_VIEW,
        ],

        TenantRole::Manager->value => [
            Capabilities::TENANT_VIEW,
            Capabilities::TENANT_MANAGE,
            Capabilities::TENANT_SYNC,

            Capabilities::TENANT_MEMBERSHIP_VIEW,
            Capabilities::TENANT_MEMBERSHIP_MANAGE,

            Capabilities::TENANT_ROLE_MAPPING_VIEW,
            Capabilities::TENANT_ROLE_MAPPING_MANAGE,

            Capabilities::PROVIDER_VIEW,
            Capabilities::PROVIDER_MANAGE,
            Capabilities::PROVIDER_RUN,

            Capabilities::AUDIT_VIEW,
        ],

        TenantRole::Operator->value => [
            Capabilities::TENANT_VIEW,
            Capabilities::TENANT_SYNC,

            Capabilities::TENANT_MEMBERSHIP_VIEW,
            Capabilities::TENANT_ROLE_MAPPING_VIEW,

            Capabilities::PROVIDER_VIEW,
            Capabilities::PROVIDER_RUN,

            Capabilities::AUDIT_VIEW,
        ],

        TenantRole::Readonly->value => [
            Capabilities::TENANT_VIEW,

            Capabilities::TENANT_MEMBERSHIP_VIEW,
            Capabilities::TENANT_ROLE_MAPPING_VIEW,

            Capabilities::PROVIDER_VIEW,

            Capabilities::AUDIT_VIEW,
        ],
    ];

    /**
     * Get all capabilities for a given role
     *
     * @return array<string>
     */
    public static function getCapabilities(TenantRole|string $role): array
    {
        $roleValue = $role instanceof TenantRole ? $role->value : $role;

        return self::$roleCapabilities[$roleValue] ?? [];
    }

    /**
     * Check if a role has a specific capability
     */
    public static function hasCapability(TenantRole|string $role, string $capability): bool
    {
        return in_array($capability, self::getCapabilities($role), true);
    }
}
