<?php

use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\Policy;
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);

test('enrollment restriction restores are preview-only and skipped on execution', function () {
    $client = new class implements GraphClientInterface
    {
        public int $applyCalls = 0;

        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->applyCalls++;

            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, []);
        }
    };

    app()->instance(GraphClientInterface::class, $client);

    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-enrollment-restriction',
        'name' => 'ManagedEnvironment Enrollment Restriction',
        'metadata' => [],
    ]);

    ensureDefaultProviderConnection($tenant);

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'enrollment-restriction-1',
        'policy_type' => 'enrollmentRestriction',
        'display_name' => 'Enrollment Restriction',
        'platform' => 'all',
    ]);

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Enrollment Restriction Backup',
        'status' => 'completed',
        'item_count' => 1,
    ]);

    $backupItem = BackupItem::create([
        'managed_environment_id' => $tenant->id,
        'backup_set_id' => $backupSet->id,
        'policy_id' => $policy->id,
        'policy_identifier' => $policy->external_id,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'payload' => [
            '@odata.type' => '#microsoft.graph.deviceEnrollmentConfiguration',
            'id' => $policy->external_id,
            'displayName' => $policy->display_name,
        ],
    ]);

    $service = app(RestoreService::class);
    $preview = $service->preview($tenant, $backupSet, [$backupItem->id]);

    $previewItem = collect($preview)->first(fn (array $item) => ($item['policy_type'] ?? null) === 'enrollmentRestriction');

    expect($previewItem)->not->toBeNull()
        ->and($previewItem['restore_mode'] ?? null)->toBe('preview-only');

    $run = $service->execute(
        tenant: $tenant,
        backupSet: $backupSet,
        selectedItemIds: [$backupItem->id],
        dryRun: false,
        actorEmail: 'tester@example.com',
        actorName: 'Tester',
    );

    expect($run->results['items'] ?? [])->toHaveCount(1);

    $result = $run->results['items'][$backupItem->id] ?? null;
    expect($result)->not->toBeNull();
    expect($result['status'] ?? null)->toBe('skipped');
    expect($result['reason'] ?? null)->toBe('preview_only');

    expect($client->applyCalls)->toBe(0);
});

test('enrollment limit restores are preview-only and skipped on execution', function () {
    $client = new class implements GraphClientInterface
    {
        public int $applyCalls = 0;

        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->applyCalls++;

            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, []);
        }
    };

    app()->instance(GraphClientInterface::class, $client);

    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-enrollment-limit',
        'name' => 'ManagedEnvironment Enrollment Limit',
        'metadata' => [],
    ]);

    ensureDefaultProviderConnection($tenant);

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'enrollment-limit-1',
        'policy_type' => 'deviceEnrollmentLimitConfiguration',
        'display_name' => 'Enrollment Limit',
        'platform' => 'all',
    ]);

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Enrollment Limit Backup',
        'status' => 'completed',
        'item_count' => 1,
    ]);

    $backupItem = BackupItem::create([
        'managed_environment_id' => $tenant->id,
        'backup_set_id' => $backupSet->id,
        'policy_id' => $policy->id,
        'policy_identifier' => $policy->external_id,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'payload' => [
            '@odata.type' => '#microsoft.graph.deviceEnrollmentLimitConfiguration',
            'id' => $policy->external_id,
            'displayName' => $policy->display_name,
            'limit' => 5,
        ],
    ]);

    $service = app(RestoreService::class);
    $preview = $service->preview($tenant, $backupSet, [$backupItem->id]);

    $previewItem = collect($preview)->first(fn (array $item) => ($item['policy_type'] ?? null) === 'deviceEnrollmentLimitConfiguration');

    expect($previewItem)->not->toBeNull()
        ->and($previewItem['restore_mode'] ?? null)->toBe('preview-only');

    $run = $service->execute(
        tenant: $tenant,
        backupSet: $backupSet,
        selectedItemIds: [$backupItem->id],
        dryRun: false,
        actorEmail: 'tester@example.com',
        actorName: 'Tester',
    );

    expect($run->results['items'] ?? [])->toHaveCount(1);

    $result = $run->results['items'][$backupItem->id] ?? null;
    expect($result)->not->toBeNull();
    expect($result['status'] ?? null)->toBe('skipped');
    expect($result['reason'] ?? null)->toBe('preview_only');

    expect($client->applyCalls)->toBe(0);
});
