<?php

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

class PolicyVersionRestoreGraphClient implements GraphClientInterface
{
    /**
     * @var array<int, array{method:string,path:string,payload:array|null}>
     */
    public array $requestCalls = [];

    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
    {
        $method = strtoupper($method);

        $this->requestCalls[] = [
            'method' => $method,
            'path' => $path,
            'payload' => $options['json'] ?? null,
        ];

        if ($method === 'GET') {
            return new GraphResponse(true, ['value' => []]);
        }

        return new GraphResponse(true, []);
    }

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

test('restore can execute from a specific policy version snapshot', function () {
    $client = new PolicyVersionRestoreGraphClient;
    app()->instance(GraphClientInterface::class, $client);

    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-version-restore',
        'name' => 'ManagedEnvironment One',
        'metadata' => [],
    ]);

    ensureDefaultProviderConnection($tenant);

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'gpo-versioned-1',
        'policy_type' => 'groupPolicyConfiguration',
        'display_name' => 'Admin Templates',
        'platform' => 'windows',
    ]);

    $snapshotWithThree = [
        'id' => $policy->external_id,
        'displayName' => $policy->display_name,
        '@odata.type' => '#microsoft.graph.groupPolicyConfiguration',
        'definitionValues' => collect(range(1, 3))
            ->map(fn (int $i) => [
                'enabled' => true,
                'definition@odata.bind' => "https://graph.microsoft.com/beta/deviceManagement/groupPolicyDefinitions('def-{$i}')",
                '#Definition_Id' => "def-{$i}",
                '#Definition_displayName' => "Setting {$i}",
            ])->all(),
    ];

    $snapshotWithFive = [
        'id' => $policy->external_id,
        'displayName' => $policy->display_name,
        '@odata.type' => '#microsoft.graph.groupPolicyConfiguration',
        'definitionValues' => collect(range(1, 5))
            ->map(fn (int $i) => [
                'enabled' => true,
                'definition@odata.bind' => "https://graph.microsoft.com/beta/deviceManagement/groupPolicyDefinitions('def-{$i}')",
                '#Definition_Id' => "def-{$i}",
                '#Definition_displayName' => "Setting {$i}",
            ])->all(),
    ];

    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' => now(),
        'snapshot' => $snapshotWithThree,
        'metadata' => ['source' => 'version_capture'],
    ]);

    $versionToRestore = PolicyVersion::create([
        'managed_environment_id' => $tenant->id,
        'policy_id' => $policy->id,
        'version_number' => 2,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'created_by' => 'tester@example.com',
        'captured_at' => now(),
        'snapshot' => $snapshotWithFive,
        'metadata' => ['source' => 'version_capture'],
    ]);

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

    $service = app(RestoreService::class);
    $run = $service->executeFromPolicyVersion(
        tenant: $tenant,
        version: $versionToRestore,
        dryRun: false,
        actorEmail: $user->email,
        actorName: $user->name,
    )->refresh();

    $backupItemId = is_array($run->requested_items) ? ($run->requested_items[0] ?? null) : null;
    expect($backupItemId)->not->toBeNull();
    $result = $run->results['items'][(int) $backupItemId] ?? null;

    expect($run->status)->toBe('completed');
    expect($result)->not->toBeNull();
    expect($result['status'] ?? null)->toBe('applied');
    expect($result['definition_value_summary']['success'] ?? null)->toBe(5);

    $definitionValueCreateCalls = collect($client->requestCalls)
        ->filter(fn (array $call) => $call['method'] === 'POST' && str_contains($call['path'], '/definitionValues'))
        ->values();

    expect($definitionValueCreateCalls)->toHaveCount(5);
});

test('restore rejects policy versions from a different tenant before creating backup artifacts', function () {
    $tenantA = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-version-restore-a',
        'name' => 'ManagedEnvironment A',
        'metadata' => [],
    ]);

    $tenantB = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-version-restore-b',
        'name' => 'ManagedEnvironment B',
        'metadata' => [],
    ]);

    $policy = Policy::create([
        'managed_environment_id' => $tenantB->id,
        'external_id' => 'gpo-versioned-wrong-tenant',
        'policy_type' => 'groupPolicyConfiguration',
        'display_name' => 'Wrong ManagedEnvironment Policy',
        'platform' => 'windows',
    ]);

    $version = PolicyVersion::create([
        'managed_environment_id' => $tenantB->id,
        'policy_id' => $policy->id,
        'version_number' => 1,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'created_by' => 'tester@example.com',
        'captured_at' => now(),
        'snapshot' => [
            'id' => $policy->external_id,
            'displayName' => $policy->display_name,
            '@odata.type' => '#microsoft.graph.groupPolicyConfiguration',
            'definitionValues' => [],
        ],
        'metadata' => ['source' => 'version_capture'],
    ]);

    $service = app(RestoreService::class);

    expect(fn () => $service->executeFromPolicyVersion(
        tenant: $tenantA,
        version: $version,
        dryRun: false,
        actorEmail: 'tester@example.com',
        actorName: 'Tester',
    ))->toThrow(\InvalidArgumentException::class, 'Policy version does not belong to the provided tenant.');

    expect(BackupSet::query()->exists())->toBeFalse();
});
