<?php

use App\Jobs\SyncPoliciesJob;
use App\Models\OperationRun;
use App\Models\ManagedEnvironment;
use App\Services\Intune\PolicySyncService;
use App\Services\OperationRunService;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;

it('marks policy sync run failed when Graph is disabled', function () {
    config(['graph.enabled' => false]);

    $tenant = ManagedEnvironment::factory()->create([
        'status' => 'active',
    ]);

    $run = OperationRun::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'type' => 'policy.sync',
        'status' => OperationRunStatus::Queued->value,
        'outcome' => OperationRunOutcome::Pending->value,
    ]);

    $job = new SyncPoliciesJob(
        tenantId: (int) $tenant->getKey(),
        types: null,
        policyIds: null,
        operationRun: $run,
    );

    $job->handle(app(PolicySyncService::class), app(OperationRunService::class));

    $run->refresh();

    expect($run->status)->toBe(OperationRunStatus::Completed->value);
    expect($run->outcome)->toBe(OperationRunOutcome::Failed->value);

    $failures = is_array($run->failure_summary ?? null) ? $run->failure_summary : [];

    expect($failures)->not->toBeEmpty();
    expect($failures[0]['code'] ?? null)->toBe('graph.disabled');
});
