<?php

use App\Models\Policy;
use App\Models\ManagedEnvironment;
use App\Services\Graph\AssignmentFetcher;
use App\Services\Graph\AssignmentFilterResolver;
use App\Services\Graph\GroupResolver;
use App\Services\Graph\ScopeTagResolver;
use App\Services\Intune\PolicyCaptureOrchestrator;
use App\Services\Intune\PolicySnapshotRedactor;
use App\Services\Intune\PolicySnapshotService;
use App\Services\Intune\VersionService;
use App\Services\Providers\MicrosoftGraphOptionsResolver;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);
test('capture returns failure when snapshot fetch fails (no exception)', function () {
    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => 'tenant-1',
        'app_client_id' => 'client-1',
        'app_client_secret' => 'secret-1',
        'is_current' => true,
    ]);

    ensureDefaultProviderConnection($tenant, 'microsoft');

    $policy = Policy::factory()->create([
        'managed_environment_id' => $tenant->id,
        'policy_type' => 'mamAppConfiguration',
        'external_id' => 'A_f38e7f58-ac7c-455d-bb0e-f56bf1b3890e',
        'display_name' => 'MAM Example',
        'platform' => 'mobile',
    ]);

    $snapshotService = Mockery::mock(PolicySnapshotService::class);
    $snapshotService
        ->shouldReceive('fetch')
        ->once()
        ->andReturn([
            'failure' => [
                'reason' => 'InternalServerError: upstream',
                'status' => 500,
            ],
        ]);

    $orchestrator = new PolicyCaptureOrchestrator(
        versionService: Mockery::mock(VersionService::class),
        snapshotService: $snapshotService,
        snapshotRedactor: new PolicySnapshotRedactor,
        assignmentFetcher: Mockery::mock(AssignmentFetcher::class),
        groupResolver: Mockery::mock(GroupResolver::class),
        assignmentFilterResolver: Mockery::mock(AssignmentFilterResolver::class),
        scopeTagResolver: Mockery::mock(ScopeTagResolver::class),
        graphOptionsResolver: app(MicrosoftGraphOptionsResolver::class),
    );

    $result = $orchestrator->capture(
        policy: $policy,
        tenant: $tenant,
        includeAssignments: true,
        includeScopeTags: true,
        createdBy: 'admin@example.test',
    );

    expect($result)->toHaveKey('failure');
    expect($result['failure']['status'])->toBe(500);
    expect($result['failure']['reason'])->toContain('InternalServerError');
});
