<?php

declare(strict_types=1);

use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Models\ProviderCredential;
use App\Models\ManagedEnvironment;
use App\Services\Providers\ProviderOperationStartGate;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\Providers\ProviderReasonCodes;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('stores provider capability context when provider operation starts', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => '44444444-4444-4444-4444-444444444444',
    ]);
    $connection = ProviderConnection::factory()->dedicated()->consentGranted()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'provider' => 'microsoft',
        'entra_tenant_id' => '44444444-4444-4444-4444-444444444444',
    ]);
    ProviderCredential::factory()->create([
        'provider_connection_id' => (int) $connection->getKey(),
    ]);

    $result = app(ProviderOperationStartGate::class)->start(
        tenant: $tenant,
        connection: $connection,
        operationType: 'provider.connection.check',
        dispatcher: fn (OperationRun $run): null => null,
    );

    $context = $result->run->fresh()->context;

    expect($result->status)->toBe('started')
        ->and($context['required_provider_capabilities'] ?? [])->toBe(['provider_connection_check'])
        ->and(data_get($context, 'provider_capabilities.0.provider_capability_key'))->toBe('provider_connection_check')
        ->and(data_get($context, 'provider_capabilities.0.status'))->toBe('supported');
});

it('preserves active operation dedupe before applying capability blockers', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => '66666666-6666-6666-6666-666666666666',
    ]);
    $connection = ProviderConnection::factory()->dedicated()->consentGranted()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'provider' => 'microsoft',
        'entra_tenant_id' => '66666666-6666-6666-6666-666666666666',
    ]);
    ProviderCredential::factory()->create([
        'provider_connection_id' => (int) $connection->getKey(),
    ]);
    $activeRun = OperationRun::factory()->forTenant($tenant)->create([
        'type' => 'directory.groups.sync',
        'status' => OperationRunStatus::Queued->value,
        'context' => [
            'provider_connection_id' => (int) $connection->getKey(),
        ],
    ]);

    $result = app(ProviderOperationStartGate::class)->start(
        tenant: $tenant,
        connection: $connection,
        operationType: 'directory.groups.sync',
        dispatcher: fn (): null => null,
    );

    expect($result->status)->toBe('deduped')
        ->and($result->run->is($activeRun))->toBeTrue();
});

it('blocks provider operations when a required provider capability is missing', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => '55555555-5555-5555-5555-555555555555',
    ]);
    $connection = ProviderConnection::factory()->dedicated()->consentGranted()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'provider' => 'microsoft',
        'entra_tenant_id' => '55555555-5555-5555-5555-555555555555',
    ]);
    ProviderCredential::factory()->create([
        'provider_connection_id' => (int) $connection->getKey(),
    ]);

    $result = app(ProviderOperationStartGate::class)->start(
        tenant: $tenant,
        connection: $connection,
        operationType: 'directory.groups.sync',
        dispatcher: fn (): null => null,
    );

    $context = $result->run->fresh()->context;

    expect($result->status)->toBe('blocked')
        ->and($result->run->outcome)->toBe(OperationRunOutcome::Blocked->value)
        ->and($context['reason_code'] ?? null)->toBe(ProviderReasonCodes::ProviderPermissionMissing)
        ->and($context['required_provider_capabilities'] ?? [])->toBe(['directory_groups_read'])
        ->and(data_get($context, 'provider_capability.provider_capability_key'))->toBe('directory_groups_read')
        ->and(data_get($context, 'provider_capability.status'))->toBe('missing');
});
