<?php

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

uses(RefreshDatabase::class);

test('assignment restore emits exactly one summary audit entry per restore execution', function () {
    app()->instance(GraphClientInterface::class, new class implements GraphClientInterface
    {
        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, []);
        }

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

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

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

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

    $tenant = ManagedEnvironment::factory()->create([
        'managed_environment_id' => 'tenant-assignment-audit-summary',
    ]);
    ensureDefaultProviderConnection($tenant);

    $policy = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => 'policy-assignment-audit-summary',
        'policy_type' => 'settingsCatalogPolicy',
    ]);

    $backupSet = BackupSet::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
    ]);

    $backupItem = BackupItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'backup_set_id' => (int) $backupSet->getKey(),
        'policy_id' => (int) $policy->getKey(),
        'policy_identifier' => (string) $policy->external_id,
        'policy_type' => (string) $policy->policy_type,
        'assignments' => [
            [
                'id' => 'assignment-1',
                'target' => [
                    '@odata.type' => '#microsoft.graph.groupAssignmentTarget',
                    'groupId' => 'group-source-1',
                ],
            ],
            [
                'id' => 'assignment-2',
                'target' => [
                    '@odata.type' => '#microsoft.graph.groupAssignmentTarget',
                    'groupId' => 'group-source-2',
                ],
            ],
        ],
        'payload' => [
            '@odata.type' => '#microsoft.graph.deviceManagementConfigurationPolicy',
        ],
    ]);

    $user = User::factory()->create([
        'email' => 'assignment.audit.summary@example.com',
    ]);
    $this->actingAs($user);

    $restoreRun = app(RestoreService::class)->execute(
        tenant: $tenant,
        backupSet: $backupSet,
        selectedItemIds: [(int) $backupItem->getKey()],
        dryRun: false,
        actorEmail: $user->email,
        actorName: $user->name,
        groupMapping: [
            'group-source-1' => 'group-target-1',
            'group-source-2' => 'group-target-2',
        ],
    );

    $summaryEntries = AuditLog::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('action', 'restore.assignments.summary')
        ->where('resource_type', 'restore_run')
        ->where('resource_id', (string) $restoreRun->getKey())
        ->get();

    expect($summaryEntries)->toHaveCount(1);
    expect($summaryEntries->first()?->metadata['succeeded'] ?? null)->toBe(2);
    expect($summaryEntries->first()?->metadata['failed'] ?? null)->toBe(0);

    $perAssignmentEntryCount = AuditLog::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->whereIn('action', [
            'restore.assignment.created',
            'restore.assignment.failed',
            'restore.assignment.skipped',
        ])
        ->count();

    expect($perAssignmentEntryCount)->toBe(0);
});
