<?php

use App\Filament\Resources\PolicyResource;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\Policy;
use App\Models\PolicyVersion;
use App\Models\ManagedEnvironment;
use App\Services\Graph\GraphClientInterface;
use App\Services\Graph\GraphResponse;
use App\Services\Intune\RestoreService;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('@odata.type mismatch is surfaced and blocks restore execution', function () {
    app()->bind(GraphClientInterface::class, fn () => 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, ['payload' => []]);
        }

        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' => 'local-tenant',
        'name' => 'ManagedEnvironment One',
        'status' => 'active',
    ]);

    ensureDefaultProviderConnection($tenant);

    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');
    $tenant->makeCurrent();

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'policy-1',
        'policy_type' => 'deviceConfiguration',
        'display_name' => 'Policy A',
        'platform' => 'windows',
    ]);

    $snapshot = [
        '@odata.type' => '#microsoft.graph.unknownConfiguration',
        'displayName' => 'Policy A',
    ];

    PolicyVersion::create([
        'managed_environment_id' => $tenant->id,
        'policy_id' => $policy->id,
        'version_number' => 1,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'created_by' => 'tester@example.com',
        'captured_at' => CarbonImmutable::now(),
        'snapshot' => $snapshot,
    ]);

    $backupSet = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => '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' => $snapshot,
    ]);

    $detailResponse = $this->actingAs($user)
        ->get(PolicyResource::getUrl('view', ['record' => $policy], tenant: $tenant));

    $detailResponse->assertSee('@odata.type mismatch');

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

    expect($run->status)->toBe('failed');

    $result = $run->results['items'][$backupItem->id] ?? null;
    expect($result)->toBeArray();
    expect($result['reason'] ?? null)->toContain('mismatch');
});
