<?php

use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\OperationRun;
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 App\Support\Providers\ProviderReasonCodes;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('assignment restore writes stable failure code and normalized reason code', 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(
                success: false,
                data: [],
                status: 400,
                errors: [
                    ['code' => 'BadRequest', 'message' => 'Bad request'],
                ],
                warnings: [],
                meta: [
                    'error_code' => 'BadRequest',
                    'error_message' => 'Bad request while restoring assignments',
                ],
            );
        }

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

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

    $policy = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => 'policy-assignment-restore-failure',
        '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',
                ],
            ],
        ],
        'payload' => [
            '@odata.type' => '#microsoft.graph.deviceManagementConfigurationPolicy',
        ],
    ]);

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

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

    $assignmentRun = OperationRun::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('type', 'assignments.restore')
        ->latest('id')
        ->first();

    expect($assignmentRun)->not->toBeNull();
    expect($assignmentRun?->status)->toBe('completed');
    expect($assignmentRun?->outcome)->toBe('failed');
    expect($assignmentRun?->summary_counts ?? [])->toMatchArray([
        'total' => 1,
        'processed' => 0,
        'failed' => 1,
    ]);

    $failure = $assignmentRun?->failure_summary[0] ?? [];

    expect($failure['code'] ?? null)->toBe('assignments.restore_failed');
    expect($failure['reason_code'] ?? null)->toBe(ProviderReasonCodes::ProviderConnectionInvalid);
    expect((string) ($failure['message'] ?? ''))->not->toBe('');
});
