<?php

namespace App\Services\Inventory;

use App\Models\InventoryItem;
use App\Models\OperationRun;
use App\Models\Policy;
use App\Models\ProviderConnection;
use App\Models\ManagedEnvironment;
use App\Services\BackupScheduling\PolicyTypeResolver;
use App\Services\Graph\GraphContractRegistry;
use App\Services\Graph\GraphResponse;
use App\Services\OperationRunService;
use App\Services\Providers\ProviderConnectionResolver;
use App\Services\Providers\ProviderGateway;
use App\Support\Inventory\InventoryCoverage;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
use App\Support\Providers\ProviderReasonCodes;
use Illuminate\Contracts\Cache\Lock;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;

class InventorySyncService
{
    public function __construct(
        private readonly PolicyTypeResolver $policyTypeResolver,
        private readonly InventorySelectionHasher $selectionHasher,
        private readonly InventoryMetaSanitizer $metaSanitizer,
        private readonly InventoryConcurrencyLimiter $concurrencyLimiter,
        private readonly ProviderConnectionResolver $providerConnections,
        private readonly ProviderGateway $providerGateway,
        private readonly GraphContractRegistry $graphContracts,
        private readonly OperationRunService $operationRuns,
    ) {}

    /**
     * Runs an inventory sync immediately and persists a canonical OperationRun.
     *
     * This is primarily used in tests and for synchronous workflows.
     *
     * @param  array<string, mixed>  $selectionPayload
     */
    public function syncNow(ManagedEnvironment $tenant, array $selectionPayload): OperationRun
    {
        $computed = $this->normalizeAndHashSelection($selectionPayload);
        $normalizedSelection = $computed['selection'];
        $selectionHash = $computed['selection_hash'];

        $operationRun = OperationRun::query()->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'managed_environment_id' => (int) $tenant->getKey(),
            'user_id' => null,
            'initiator_name' => 'System',
            'type' => OperationRunType::InventorySync->value,
            'status' => OperationRunStatus::Running->value,
            'outcome' => OperationRunOutcome::Pending->value,
            'run_identity_hash' => hash('sha256', (string) $tenant->getKey().':'.OperationRunType::InventorySync->value.':'.$selectionHash.':'.Str::uuid()->toString()),
            'context' => array_merge($normalizedSelection, [
                'selection_hash' => $selectionHash,
            ]),
            'started_at' => now(),
        ]);

        $policyTypes = $normalizedSelection['policy_types'] ?? [];
        $policyTypes = is_array($policyTypes) ? $policyTypes : [];
        $foundationTypes = $this->foundationTypes();
        $includeFoundations = (bool) ($normalizedSelection['include_foundations'] ?? false);

        $attemptedTypes = $includeFoundations
            ? array_values(array_unique(array_merge($policyTypes, $foundationTypes)))
            : array_values(array_diff($policyTypes, $foundationTypes));

        $statusByType = [];

        foreach ($attemptedTypes as $type) {
            if (! is_string($type) || $type === '') {
                continue;
            }

            $statusByType[$type] = [
                'status' => InventoryCoverage::StatusSkipped,
                'item_count' => 0,
            ];
        }

        $result = $this->executeSelection(
            $operationRun,
            $tenant,
            $normalizedSelection,
            function (string $policyType, bool $success, ?string $errorCode, int $itemCount) use (&$statusByType): void {
                $statusByType[$policyType] = array_filter([
                    'status' => $success
                        ? InventoryCoverage::StatusSucceeded
                        : InventoryCoverage::StatusFailed,
                    'item_count' => $itemCount,
                    'error_code' => $success ? null : $errorCode,
                ], static fn (mixed $value): bool => $value !== null);
            },
        );

        $status = (string) ($result['status'] ?? 'failed');
        $hadErrors = (bool) ($result['had_errors'] ?? true);
        $errorCodes = is_array($result['error_codes'] ?? null) ? array_values($result['error_codes']) : [];
        $errorContext = is_array($result['error_context'] ?? null) ? $result['error_context'] : null;

        $operationOutcome = match ($status) {
            'success' => OperationRunOutcome::Succeeded->value,
            'partial' => OperationRunOutcome::PartiallySucceeded->value,
            'skipped' => OperationRunOutcome::Blocked->value,
            default => OperationRunOutcome::Failed->value,
        };

        $failureSummary = [];

        if ($hadErrors && $errorCodes !== []) {
            foreach (array_values(array_unique($errorCodes)) as $errorCode) {
                if (! is_string($errorCode) || $errorCode === '') {
                    continue;
                }

                $failureSummary[] = [
                    'code' => $errorCode,
                    'message' => sprintf('Inventory sync reported %s.', str_replace('_', ' ', $errorCode)),
                ];
            }
        }

        $updatedContext = is_array($operationRun->context) ? $operationRun->context : [];

        $coverageStatusByType = $statusByType;
        $skippedErrorCode = is_string($errorCodes[0] ?? null) ? (string) $errorCodes[0] : null;

        if ($status === 'skipped') {
            foreach ($coverageStatusByType as $type => $coverageStatus) {
                $coverageStatusByType[$type] = array_filter([
                    'status' => InventoryCoverage::StatusSkipped,
                    'item_count' => 0,
                    'error_code' => $skippedErrorCode,
                ], static fn (mixed $value): bool => $value !== null);
            }
        }

        $updatedContext['inventory'] = array_merge(
            is_array($updatedContext['inventory'] ?? null) ? $updatedContext['inventory'] : [],
            [
                'coverage' => InventoryCoverage::buildPayload(
                    statusByType: $coverageStatusByType,
                    foundationTypes: $foundationTypes,
                ),
            ],
        );
        $updatedContext['result'] = [
            'had_errors' => $hadErrors,
            'error_codes' => $errorCodes,
            'error_context' => $errorContext,
        ];

        $operationRun->update([
            'context' => $updatedContext,
        ]);

        $this->operationRuns->updateRun(
            $operationRun,
            status: OperationRunStatus::Completed->value,
            outcome: $operationOutcome,
            summaryCounts: [
                'total' => count($policyTypes),
                'processed' => count($policyTypes),
                'succeeded' => $status === 'success' ? count($policyTypes) : max(0, count($policyTypes) - (int) ($result['errors_count'] ?? 0)),
                'failed' => (int) ($result['errors_count'] ?? 0),
                'items' => (int) ($result['items_observed_count'] ?? 0),
                'updated' => (int) ($result['items_upserted_count'] ?? 0),
            ],
            failures: $failureSummary,
        );

        return $operationRun->refresh();
    }

    /**
     * Runs an inventory sync (inline), enforcing locks/concurrency.
     *
     * This method MUST NOT create or update legacy sync-run rows; OperationRun is canonical.
     *
     * @param  array<string, mixed>  $selectionPayload
     * @param  null|callable(string $policyType, bool $success, ?string $errorCode, int $itemCount): void  $onPolicyTypeProcessed
     * @return array{status: string, had_errors: bool, error_codes: list<string>, error_context: array<string, mixed>|null, items_observed_count: int, items_upserted_count: int, errors_count: int}
     */
    public function executeSelection(OperationRun $operationRun, ManagedEnvironment $tenant, array $selectionPayload, ?callable $onPolicyTypeProcessed = null): array
    {
        $computed = $this->normalizeAndHashSelection($selectionPayload);
        $normalizedSelection = $computed['selection'];
        $selectionHash = $computed['selection_hash'];

        $globalSlot = $this->concurrencyLimiter->acquireGlobalSlot();
        if (! $globalSlot instanceof Lock) {
            return $this->skippedResult('concurrency_limit_global');
        }

        $tenantSlot = $this->concurrencyLimiter->acquireTenantSlot((int) $tenant->id);
        if (! $tenantSlot instanceof Lock) {
            $globalSlot->release();

            return $this->skippedResult('concurrency_limit_tenant');
        }

        $selectionLock = Cache::lock($this->selectionLockKey($tenant, $selectionHash), 900);
        if (! $selectionLock->get()) {
            $tenantSlot->release();
            $globalSlot->release();

            return $this->skippedResult('lock_contended');
        }

        try {
            return $this->executeSelectionUnderLock($operationRun, $tenant, $normalizedSelection, $onPolicyTypeProcessed);
        } finally {
            $selectionLock->release();
            $tenantSlot->release();
            $globalSlot->release();
        }
    }

    /**
     * @return array{policy_types: list<string>, categories: list<string>, include_foundations: bool, include_dependencies: bool}
     */
    public function defaultSelectionPayload(): array
    {
        return [
            'policy_types' => $this->policyTypeResolver->supportedPolicyTypes(),
            'categories' => [],
            'include_foundations' => true,
            'include_dependencies' => true,
        ];
    }

    /**
     * @param  array<string, mixed>  $selectionPayload
     * @return array{selection: array{policy_types: list<string>, categories: list<string>, include_foundations: bool, include_dependencies: bool}, selection_hash: string}
     */
    public function normalizeAndHashSelection(array $selectionPayload): array
    {
        $normalizedSelection = $this->selectionHasher->normalize($selectionPayload);
        $normalizedSelection['policy_types'] = $this->policyTypeResolver->filterRuntime($normalizedSelection['policy_types']);
        $selectionHash = $this->selectionHasher->hash($normalizedSelection);

        return [
            'selection' => $normalizedSelection,
            'selection_hash' => $selectionHash,
        ];
    }

    /**
     * @param  array{policy_types: list<string>, categories: list<string>, include_foundations: bool, include_dependencies: bool}  $normalizedSelection
     * @param  null|callable(string $policyType, bool $success, ?string $errorCode, int $itemCount): void  $onPolicyTypeProcessed
     * @return array{status: string, had_errors: bool, error_codes: list<string>, error_context: array<string, mixed>|null, items_observed_count: int, items_upserted_count: int, errors_count: int}
     */
    private function executeSelectionUnderLock(OperationRun $operationRun, ManagedEnvironment $tenant, array $normalizedSelection, ?callable $onPolicyTypeProcessed = null): array
    {
        $observed = 0;
        $upserted = 0;
        $errors = 0;
        $errorCodes = [];
        $hadErrors = false;
        $warnings = [];
        $observedByType = [];

        try {
            $connection = $this->resolveProviderConnection($tenant);
            $typesConfig = $this->supportedTypeConfigByType();

            $policyTypes = $normalizedSelection['policy_types'] ?? [];
            $foundationTypes = $this->foundationTypes();

            if ((bool) ($normalizedSelection['include_foundations'] ?? false)) {
                $policyTypes = array_values(array_unique(array_merge($policyTypes, $foundationTypes)));
            } else {
                $policyTypes = array_values(array_diff($policyTypes, $foundationTypes));
            }

            foreach ($policyTypes as $policyType) {
                $typeConfig = $typesConfig[$policyType] ?? null;

                if (! is_array($typeConfig)) {
                    $hadErrors = true;
                    $errors++;
                    $errorCodes[] = 'unsupported_type';
                    $onPolicyTypeProcessed && $onPolicyTypeProcessed($policyType, false, 'unsupported_type', 0);

                    continue;
                }

                $response = $this->listPoliciesWithRetry(
                    $policyType,
                    $this->listOptionsForPolicyType($policyType, $typeConfig),
                    $connection
                );

                if ($response->failed()) {
                    $hadErrors = true;
                    $errors++;
                    $errorCode = $this->mapGraphFailureToErrorCode($response);
                    $errorCodes[] = $errorCode;
                    $onPolicyTypeProcessed && $onPolicyTypeProcessed($policyType, false, $errorCode, 0);

                    continue;
                }

                foreach ($response->data as $policyData) {
                    if (! is_array($policyData)) {
                        continue;
                    }

                    if ($this->shouldSkipPolicyForSelectedType($policyType, $policyData)) {
                        continue;
                    }

                    $externalId = $policyData['id'] ?? $policyData['external_id'] ?? null;
                    if (! is_string($externalId) || $externalId === '') {
                        continue;
                    }

                    $observed++;
                    $observedByType[$policyType] = (int) ($observedByType[$policyType] ?? 0) + 1;

                    $includeDeps = (bool) ($normalizedSelection['include_dependencies'] ?? true);

                    if ($includeDeps && $this->shouldHydrateAssignments($policyType)) {
                        $existingAssignments = $policyData['assignments'] ?? null;
                        if (! is_array($existingAssignments) || count($existingAssignments) === 0) {
                            $hydratedAssignments = $this->fetchAssignmentsForPolicyType($policyType, $connection, $externalId, $warnings);
                            if (is_array($hydratedAssignments)) {
                                $policyData['assignments'] = $hydratedAssignments;
                            }
                        }
                    }

                    $displayName = $policyData['displayName'] ?? $policyData['name'] ?? null;
                    $displayName = is_string($displayName) ? $displayName : null;

                    $scopeTagIds = $policyData['roleScopeTagIds'] ?? null;
                    $assignmentTargetCount = null;
                    $assignments = $policyData['assignments'] ?? null;
                    if (is_array($assignments)) {
                        $assignmentTargetCount = count($assignments);
                    }

                    $meta = $this->metaSanitizer->sanitize([
                        'odata_type' => $policyData['@odata.type'] ?? $policyData['@OData.Type'] ?? null,
                        'etag' => $policyData['@odata.etag'] ?? null,
                        'scope_tag_ids' => is_array($scopeTagIds) ? $scopeTagIds : null,
                        'assignment_target_count' => $assignmentTargetCount,
                        ...$this->rbacMeta($policyType, $policyData),
                        'warnings' => [],
                    ]);

                    $item = InventoryItem::query()->updateOrCreate(
                        [
                            'managed_environment_id' => $tenant->getKey(),
                            'policy_type' => $policyType,
                            'external_id' => $externalId,
                        ],
                        [
                            'workspace_id' => $tenant->workspace_id,
                            'display_name' => $displayName,
                            'category' => $typeConfig['category'] ?? null,
                            'platform' => $typeConfig['platform'] ?? null,
                            'meta_jsonb' => $meta,
                            'last_seen_at' => now(),
                            'last_seen_operation_run_id' => (int) $operationRun->getKey(),
                        ]
                    );

                    if ($this->supportsFoundationVersioning($policyType)) {
                        $this->resolveFoundationPolicyAnchor(
                            tenant: $tenant,
                            foundationType: $policyType,
                            sourceId: $externalId,
                            platform: is_string($typeConfig['platform'] ?? null) ? $typeConfig['platform'] : null,
                            displayName: $displayName,
                        );
                    }

                    $upserted++;

                    // Extract dependencies if requested in selection
                    if ($includeDeps) {
                        $warnings = array_merge(
                            $warnings,
                            app(\App\Services\Inventory\DependencyExtractionService::class)
                                ->extractForPolicyData($item, $policyData)
                        );
                    }
                }

                $onPolicyTypeProcessed && $onPolicyTypeProcessed(
                    $policyType,
                    true,
                    null,
                    (int) ($observedByType[$policyType] ?? 0),
                );
            }

            return [
                'status' => $hadErrors ? 'partial' : 'success',
                'had_errors' => $hadErrors,
                'error_codes' => array_values(array_unique($errorCodes)),
                'error_context' => [
                    'warnings' => array_values($warnings),
                ],
                'items_observed_count' => $observed,
                'items_upserted_count' => $upserted,
                'errors_count' => $errors,
            ];
        } catch (Throwable $throwable) {
            $errorContext = $this->safeErrorContext($throwable);
            $errorContext['warnings'] = array_values($warnings);

            return [
                'status' => 'failed',
                'had_errors' => true,
                'error_codes' => ['unexpected_exception'],
                'error_context' => $errorContext,
                'items_observed_count' => $observed,
                'items_upserted_count' => $upserted,
                'errors_count' => $errors + 1,
            ];
        }
    }

    /**
     * @return array{status: string, had_errors: bool, error_codes: list<string>, error_context: array<string, mixed>|null, items_observed_count: int, items_upserted_count: int, errors_count: int}
     */
    private function skippedResult(string $errorCode): array
    {
        return [
            'status' => 'skipped',
            'had_errors' => true,
            'error_codes' => [$errorCode],
            'error_context' => null,
            'items_observed_count' => 0,
            'items_upserted_count' => 0,
            'errors_count' => 0,
        ];
    }

    private function shouldSkipPolicyForSelectedType(string $selectedPolicyType, array $policyData): bool
    {
        $configurationPolicyTypes = ['settingsCatalogPolicy', 'endpointSecurityPolicy', 'securityBaselinePolicy'];

        if (! in_array($selectedPolicyType, $configurationPolicyTypes, true)) {
            return false;
        }

        return $this->resolveConfigurationPolicyType($policyData) !== $selectedPolicyType;
    }

    private function shouldHydrateAssignments(string $policyType): bool
    {
        return in_array($policyType, ['settingsCatalogPolicy', 'endpointSecurityPolicy', 'securityBaselinePolicy'], true);
    }

    private function supportsFoundationVersioning(string $foundationType): bool
    {
        return in_array($foundationType, ['intuneRoleDefinition', 'intuneRoleAssignment'], true);
    }

    /**
     * @param  array<int, array<string, mixed>>  $warnings
     * @return null|array<int, mixed>
     */
    private function fetchAssignmentsForPolicyType(string $policyType, ProviderConnection $connection, string $externalId, array &$warnings): ?array
    {
        $pathTemplate = config("graph_contracts.types.{$policyType}.assignments_list_path");
        if (! is_string($pathTemplate) || $pathTemplate === '') {
            return null;
        }

        $path = str_replace('{id}', $externalId, $pathTemplate);

        $maxAttempts = 3;

        for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
            $response = $this->providerGateway->request($connection, 'GET', $path);

            if (! $response->failed()) {
                $data = $response->data;
                if (is_array($data) && array_key_exists('value', $data) && is_array($data['value'])) {
                    return $data['value'];
                }

                if (is_array($data)) {
                    return $data;
                }

                return null;
            }

            $status = (int) ($response->status ?? 0);
            if (! in_array($status, [429, 503], true)) {
                break;
            }
        }

        $warning = [
            'type' => 'assignments_fetch_failed',
            'policy_id' => $externalId,
            'policy_type' => $policyType,
            'reason' => 'graph_assignments_list_failed',
        ];

        $warnings[] = $warning;
        Log::info('Failed to fetch policy assignments', $warning);

        return null;
    }

    private function resolveConfigurationPolicyType(array $policyData): string
    {
        $templateReference = $policyData['templateReference'] ?? null;
        $templateFamily = null;
        if (is_array($templateReference)) {
            $templateFamily = $templateReference['templateFamily'] ?? null;
        }

        if (is_string($templateFamily) && strcasecmp(trim($templateFamily), 'securityBaseline') === 0) {
            return 'securityBaselinePolicy';
        }

        if ($this->isEndpointSecurityConfigurationPolicy($policyData, $templateFamily)) {
            return 'endpointSecurityPolicy';
        }

        return 'settingsCatalogPolicy';
    }

    private function isEndpointSecurityConfigurationPolicy(array $policyData, ?string $templateFamily): bool
    {
        $technologies = $policyData['technologies'] ?? null;

        if (is_string($technologies) && strcasecmp(trim($technologies), 'endpointSecurity') === 0) {
            return true;
        }

        if (is_array($technologies)) {
            foreach ($technologies as $technology) {
                if (is_string($technology) && strcasecmp(trim($technology), 'endpointSecurity') === 0) {
                    return true;
                }
            }
        }

        return is_string($templateFamily) && str_starts_with(strtolower(trim($templateFamily)), 'endpointsecurity');
    }

    /**
     * @return array<string, array<string, mixed>>
     */
    private function supportedTypeConfigByType(): array
    {
        /** @var array<int, array<string, mixed>> $supported */
        $supported = config('tenantpilot.supported_policy_types', []);

        /** @var array<int, array<string, mixed>> $foundations */
        $foundations = config('tenantpilot.foundation_types', []);

        $all = array_merge(
            is_array($supported) ? $supported : [],
            is_array($foundations) ? $foundations : [],
        );

        $byType = [];
        foreach ($all as $config) {
            $type = $config['type'] ?? null;
            if (is_string($type) && $type !== '') {
                $byType[$type] = $config;
            }
        }

        return $byType;
    }

    /**
     * @return list<string>
     */
    private function foundationTypes(): array
    {
        $types = config('tenantpilot.foundation_types', []);
        if (! is_array($types)) {
            return [];
        }

        return collect($types)
            ->map(fn (array $row) => $row['type'] ?? null)
            ->filter(fn ($type) => is_string($type) && $type !== '')
            ->values()
            ->all();
    }

    /**
     * @param  array<string, mixed>  $typeConfig
     * @return array<string, mixed>
     */
    private function listOptionsForPolicyType(string $policyType, array $typeConfig): array
    {
        $options = [
            'platform' => $typeConfig['platform'] ?? null,
            'filter' => $typeConfig['filter'] ?? null,
        ];

        if (! in_array($policyType, $this->foundationTypes(), true)) {
            return $options;
        }

        $expand = $this->graphContracts->get($policyType)['allowed_expand'] ?? [];

        if (is_array($expand) && $expand !== []) {
            $options['expand'] = $expand;
        }

        return $options;
    }

    /**
     * @param  array<string, mixed>  $policyData
     * @return array<string, mixed>
     */
    private function rbacMeta(string $policyType, array $policyData): array
    {
        if ($policyType === 'intuneRoleDefinition') {
            $rolePermissions = $policyData['rolePermissions'] ?? null;

            return [
                'is_built_in' => is_bool($policyData['isBuiltIn'] ?? null) ? $policyData['isBuiltIn'] : null,
                'role_permission_count' => is_array($rolePermissions) ? count($rolePermissions) : null,
            ];
        }

        if ($policyType !== 'intuneRoleAssignment') {
            return [];
        }

        $roleDefinition = $policyData['roleDefinition'] ?? null;
        $members = $policyData['members'] ?? null;
        $scopeMembers = $policyData['scopeMembers'] ?? null;
        $resourceScopes = $policyData['resourceScopes'] ?? null;

        return [
            'role_definition_id' => is_array($roleDefinition) && is_string($roleDefinition['id'] ?? null)
                ? $roleDefinition['id']
                : (is_string($policyData['roleDefinitionId'] ?? null) ? $policyData['roleDefinitionId'] : null),
            'role_definition_name' => is_array($roleDefinition) && is_string($roleDefinition['displayName'] ?? null)
                ? $roleDefinition['displayName']
                : null,
            'member_count' => is_array($members) ? count($members) : null,
            'scope_member_count' => is_array($scopeMembers) ? count($scopeMembers) : null,
            'resource_scope_count' => is_array($resourceScopes) ? count($resourceScopes) : null,
        ];
    }

    private function resolveFoundationPolicyAnchor(
        ManagedEnvironment $tenant,
        string $foundationType,
        string $sourceId,
        ?string $platform,
        ?string $displayName,
    ): Policy {
        $policy = Policy::query()->firstOrNew([
            'managed_environment_id' => $tenant->getKey(),
            'external_id' => $sourceId,
            'policy_type' => $foundationType,
        ]);

        $existingMetadata = is_array($policy->metadata) ? $policy->metadata : [];

        $policy->fill([
            'platform' => $platform,
            'display_name' => is_string($displayName) && $displayName !== '' ? $displayName : $sourceId,
            'last_synced_at' => null,
            'metadata' => array_merge(
                $existingMetadata,
                [
                    'foundation_anchor' => true,
                    'foundation_type' => $foundationType,
                    'capture_mode' => 'immutable_backup',
                ],
            ),
        ]);
        $policy->save();

        return $policy;
    }

    private function selectionLockKey(ManagedEnvironment $tenant, string $selectionHash): string
    {
        return sprintf('%s:tenant:%s:selection:%s', OperationRunType::InventorySync->value, (string) $tenant->getKey(), $selectionHash);
    }

    private function mapGraphFailureToErrorCode(GraphResponse $response): string
    {
        $status = (int) ($response->status ?? 0);

        return match ($status) {
            403 => 'graph_forbidden',
            429 => 'graph_throttled',
            503 => 'graph_transient',
            default => 'graph_transient',
        };
    }

    private function listPoliciesWithRetry(string $policyType, array $options, ProviderConnection $connection): GraphResponse
    {
        $maxAttempts = 3;

        for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
            $response = $this->providerGateway->listPolicies($connection, $policyType, $options);

            if (! $response->failed()) {
                return $response;
            }

            $status = (int) ($response->status ?? 0);
            if (! in_array($status, [429, 503], true)) {
                return $response;
            }

            if ($attempt >= $maxAttempts) {
                return $response;
            }

            $baseMs = 250 * (2 ** ($attempt - 1));
            $jitterMs = random_int(0, 250);
            usleep(($baseMs + $jitterMs) * 1000);
        }

        return new GraphResponse(false, [], null, ['error' => ['code' => 'unexpected_exception', 'message' => 'retry loop failed']]);
    }

    /**
     * @throws RuntimeException
     */
    private function resolveProviderConnection(ManagedEnvironment $tenant): ProviderConnection
    {
        $resolution = $this->providerConnections->resolveDefault($tenant, 'microsoft');

        if (! $resolution->resolved || ! $resolution->connection instanceof ProviderConnection) {
            $reasonCode = $resolution->effectiveReasonCode();
            $reasonMessage = $resolution->message ?? 'Provider connection is not configured.';

            throw new RuntimeException(sprintf(
                '[%s] %s',
                ProviderReasonCodes::isKnown($reasonCode) ? $reasonCode : ProviderReasonCodes::UnknownError,
                $reasonMessage,
            ));
        }

        return $resolution->connection;
    }

    /**
     * @return array<string, mixed>
     */
    private function safeErrorContext(Throwable $throwable): array
    {
        $message = $throwable->getMessage();

        $message = preg_replace('/Bearer\s+[A-Za-z0-9\-\._~\+\/]+=*/', 'Bearer [REDACTED]', (string) $message);
        $message = mb_substr((string) $message, 0, 500);

        return [
            'exception_class' => get_class($throwable),
            'message' => $message,
        ];
    }
}
