<?php

namespace App\Support\Operations;

use App\Models\OperationRun;
use App\Support\Auth\Capabilities;
use App\Support\OperationCatalog;

final class OperationRunCapabilityResolver
{
    public function requiredCapabilityForRun(OperationRun $run): ?string
    {
        return $this->requiredCapabilityForType((string) $run->type);
    }

    public function requiredCapabilityForType(string $operationType): ?string
    {
        $operationType = OperationCatalog::canonicalCode($operationType);

        if ($operationType === '') {
            return null;
        }

        return match ($operationType) {
            'inventory.sync' => Capabilities::TENANT_INVENTORY_SYNC_RUN,
            'directory.groups.sync' => Capabilities::TENANT_SYNC,
            'backup.schedule.execute', 'backup.schedule.retention', 'backup.schedule.purge' => Capabilities::TENANT_BACKUP_SCHEDULES_RUN,
            'restore.execute', 'promotion.execute' => Capabilities::TENANT_MANAGE,
            'directory.role_definitions.sync' => Capabilities::TENANT_MANAGE,
            'alerts.evaluate', 'alerts.deliver' => Capabilities::ALERTS_VIEW,
            'environment.review.compose' => Capabilities::ENVIRONMENT_REVIEW_VIEW,

            // Viewing verification reports should be possible for readonly members.
            // Starting verification is separately guarded by the verification service.
            'provider.connection.check' => Capabilities::PROVIDER_VIEW,

            // Keep legacy / unknown types viewable by membership+entitlement only.
            default => null,
        };
    }

    public function requiredExecutionCapabilityForType(string $operationType): ?string
    {
        $operationType = OperationCatalog::canonicalCode($operationType);

        if ($operationType === '') {
            return null;
        }

        return match ($operationType) {
            'provider.connection.check', 'inventory.sync', 'compliance.snapshot' => Capabilities::PROVIDER_RUN,
            'policy.sync', 'tenant.sync' => Capabilities::TENANT_SYNC,
            'policy.delete' => Capabilities::TENANT_MANAGE,
            'assignments.restore', 'restore.execute', 'promotion.execute' => Capabilities::TENANT_MANAGE,
            'environment.review.compose' => Capabilities::ENVIRONMENT_REVIEW_MANAGE,
            default => $this->requiredCapabilityForType($operationType),
        };
    }
}
