<?php

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

uses(RefreshDatabase::class);

class RestoreScopeTagGraphClient implements GraphClientInterface
{
    /**
     * @var array<int, array{policyType:string,policyId:string,payload:array}>
     */
    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,
        ];

        return new GraphResponse(true, []);
    }

    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 applies scope tag mappings to policy payloads', function () {
    $client = new RestoreScopeTagGraphClient;
    app()->instance(GraphClientInterface::class, $client);

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

    ensureDefaultProviderConnection($tenant);

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

    $scopeTagItem = BackupItem::factory()
        ->for($tenant)
        ->for($backupSet)
        ->state([
            'policy_id' => null,
            'policy_identifier' => 'tag-old',
            'policy_type' => 'roleScopeTag',
            'platform' => 'all',
            'payload' => [
                'id' => 'tag-old',
                'displayName' => 'Scope Tag Alpha',
            ],
            'metadata' => [
                'displayName' => 'Scope Tag Alpha',
            ],
        ])
        ->create();

    $policyItem = BackupItem::factory()
        ->for($tenant)
        ->for($backupSet)
        ->state([
            'policy_id' => null,
            'policy_identifier' => 'policy-1',
            'policy_type' => 'settingsCatalogPolicy',
            'platform' => 'windows',
            'payload' => [
                'id' => 'policy-1',
                'displayName' => 'Policy Alpha',
                '@odata.type' => '#microsoft.graph.deviceManagementConfigurationPolicy',
                'roleScopeTagIds' => ['tag-old'],
            ],
        ])
        ->create();

    $entries = [
        [
            'type' => 'roleScopeTag',
            'sourceId' => 'tag-old',
            'sourceName' => 'Scope Tag Alpha',
            'decision' => 'created',
            'targetId' => 'tag-new',
            'targetName' => 'Scope Tag Alpha',
        ],
    ];

    $this->mock(FoundationMappingService::class, function (MockInterface $mock) use ($entries) {
        $mock->shouldReceive('map')
            ->twice()
            ->andReturn([
                'entries' => $entries,
                'mapping' => ['tag-old' => 'tag-new'],
                'failed' => 0,
                'skipped' => 0,
            ]);
    });

    $user = User::factory()->create();
    $this->actingAs($user);

    $service = app(RestoreService::class);
    $service->execute(
        tenant: $tenant,
        backupSet: $backupSet,
        selectedItemIds: [$scopeTagItem->id, $policyItem->id],
        dryRun: false,
        actorEmail: $user->email,
        actorName: $user->name,
    );

    expect($client->applyPolicyCalls)->toHaveCount(1);
    expect($client->applyPolicyCalls[0]['payload']['roleScopeTagIds'])->toBe(['tag-new']);
});
