<?php

use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\ManagedEnvironment;
use App\Services\Graph\GraphClientInterface;
use App\Services\Graph\GraphResponse;
use App\Services\Intune\RestoreService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

class RestoreGraphErrorMetadataGraphClient implements GraphClientInterface
{
    /** @var array<int, array{policyType:string,policyId:string,payload:array,options:array<string,mixed>}> */
    public array $applyPolicyCalls = [];

    public function listPolicies(string $policyType, array $options = []): GraphResponse
    {
        return new GraphResponse(true, []);
    }

    public function getPolicy(string $policyType, string $policyId, array $options = []): GraphResponse
    {
        return new GraphResponse(true, ['payload' => []]);
    }

    public function getOrganization(array $options = []): GraphResponse
    {
        return new GraphResponse(true, []);
    }

    public function applyPolicy(string $policyType, string $policyId, array $payload, array $options = []): GraphResponse
    {
        $this->applyPolicyCalls[] = [
            'policyType' => $policyType,
            'policyId' => $policyId,
            'payload' => $payload,
            'options' => $options,
        ];

        return new GraphResponse(false, ['error' => ['message' => 'Bad request']], 400, [], [], [
            'error_code' => 'BadRequest',
            'error_message' => "Resource not found for the segment 'endpointSecurityPolicy'.",
            'request_id' => 'req-1',
            'client_request_id' => 'client-1',
            'method' => 'PATCH',
            'path' => 'deviceManagement/endpointSecurityPolicy/esp-1',
        ]);
    }

    public function getServicePrincipalPermissions(array $options = []): GraphResponse
    {
        return new GraphResponse(true, []);
    }

    public function request(string $method, string $path, array $options = []): GraphResponse
    {
        return new GraphResponse(true, []);
    }
}

test('restore results include graph path and method on Graph failures', function () {
    $client = new RestoreGraphErrorMetadataGraphClient;
    app()->instance(GraphClientInterface::class, $client);

    $tenant = ManagedEnvironment::factory()->create();

    ensureDefaultProviderConnection($tenant);
    $backupSet = BackupSet::factory()->for($tenant)->create([
        'status' => 'completed',
        'item_count' => 1,
    ]);

    $backupItem = BackupItem::factory()->for($tenant)->for($backupSet)->create([
        'policy_id' => null,
        'policy_identifier' => 'esp-1',
        'policy_type' => 'endpointSecurityPolicy',
        'platform' => 'windows',
        'payload' => [
            'id' => 'esp-1',
            '@odata.type' => '#microsoft.graph.deviceManagementConfigurationPolicy',
            'name' => 'Endpoint Security Policy',
            'settings' => [],
        ],
        'assignments' => null,
    ]);

    $service = app(RestoreService::class);
    $run = $service->execute(
        tenant: $tenant,
        backupSet: $backupSet,
        selectedItemIds: [$backupItem->id],
        dryRun: false,
    );

    expect($client->applyPolicyCalls)->toHaveCount(1);
    expect($run->status)->toBe('failed');

    $result = $run->results['items'][$backupItem->id] ?? null;
    expect($result)->toBeArray();
    expect($result['graph_method'] ?? null)->toBe('PATCH');
    expect($result['graph_path'] ?? null)->toBe('deviceManagement/endpointSecurityPolicy/esp-1');
});
