<?php

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

uses(RefreshDatabase::class);

test('settings catalog restore marks manual_required when bulk apply returns 404', function () {
    $policyResponse = new GraphResponse(
        success: true,
        data: [],
        status: 200,
        errors: [],
        warnings: [],
        meta: ['request_id' => 'req-policy', 'client_request_id' => 'client-policy'],
    );

    $settingResponse = new GraphResponse(
        success: false,
        data: ['error' => ['code' => 'NotFound', 'message' => 'Setting missing']],
        status: 404,
        errors: [['code' => 'NotFound', 'message' => 'Setting missing']],
        warnings: [],
        meta: [
            'error_code' => 'NotFound',
            'error_message' => 'Setting missing',
            'request_id' => 'req-setting-404',
            'client_request_id' => 'client-setting-404',
        ],
    );

    $client = new class($policyResponse, $settingResponse) implements GraphClientInterface
    {
        /**
         * @var array<int, array{policy_type:string,policy_id:string,payload:array}>
         */
        public array $applyPolicyCalls = [];

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

        public function __construct(
            private readonly GraphResponse $policyResponse,
            private readonly GraphResponse $settingResponse,
        ) {}

        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->applyPolicyCalls[] = [
                'policy_type' => $policyType,
                'policy_id' => $policyId,
                'payload' => $payload,
            ];

            return $this->policyResponse;
        }

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

        public function request(string $method, string $path, array $options = []): GraphResponse
        {
            $this->requestCalls[] = [
                'method' => strtoupper($method),
                'path' => $path,
                'payload' => $options['json'] ?? null,
            ];

            return $this->settingResponse;
        }
    };

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

    $tenant = ManagedEnvironment::create([
        'managed_environment_id' => 'tenant-3',
        'name' => 'ManagedEnvironment Three',
        'metadata' => [],
    ]);

    ensureDefaultProviderConnection($tenant);

    $policy = Policy::create([
        'managed_environment_id' => $tenant->id,
        'external_id' => 'scp-3',
        'policy_type' => 'settingsCatalogPolicy',
        'display_name' => 'Settings Catalog Gamma',
        'platform' => 'windows',
    ]);

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

    $payload = [
        'displayName' => 'Settings Catalog Gamma',
        'Settings' => [
            [
                'id' => 'setting-404',
                'settingInstance' => [
                    '@odata.type' => '#microsoft.graph.deviceManagementConfigurationSimpleSettingInstance',
                    'settingDefinitionId' => 'setting_definition',
                    'simpleSettingValue' => [
                        '@odata.type' => '#microsoft.graph.deviceManagementConfigurationStringSettingValue',
                        'value' => 'test-value',
                    ],
                ],
            ],
        ],
    ];

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

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

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

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

    expect($run->status)->toBe('partial');
    expect($result['status'] ?? null)->toBe('manual_required');
    expect($result['settings_apply']['manual_required'] ?? null)->toBe(1);
    expect($result['settings_apply']['failed'] ?? null)->toBe(0);
    expect($result['settings_apply']['issues'][0]['graph_request_id'] ?? null)->toBe('req-setting-404');

    expect($client->applyPolicyCalls[0]['payload'])->not->toHaveKey('settings');
    expect($client->requestCalls[0]['method'])->toBe('POST');
    expect($client->requestCalls[0]['path'])->toBe('deviceManagement/configurationPolicies/scp-3/settings');

    $results = $run->results;
    $results['items'][$backupItem->id]['assignment_summary'] = [
        'success' => 0,
        'failed' => 1,
        'skipped' => 0,
    ];
    $results['items'][$backupItem->id]['assignment_outcomes'] = [[
        'status' => 'failed',
        'group_id' => 'group-1',
        'mapped_group_id' => 'group-2',
        'reason' => 'Graph create failed',
        'graph_error_message' => 'Bad request',
    ]];

    $run->update(['results' => $results]);

    $response = $this->withSession([
        \App\Support\Workspaces\WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
        \App\Support\Workspaces\WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY => [
            (string) $tenant->workspace_id => (int) $tenant->getKey(),
        ],
    ])->get(\App\Filament\Resources\RestoreRunResource::getUrl('view', ['record' => $run], panel: 'admin', tenant: $tenant));
    $response->assertOk();
    $response->assertSee('The restore reached a terminal state, but some items or assignments still need follow-up.');
    $response->assertSee('Manual follow-up needed');
    $response->assertSee('Graph bulk apply failed');
    $response->assertSee('Setting missing');
    $response->assertSee('req-setting-404');
    $response->assertSee('Assignments: 0 applied');
    $response->assertSee('Assignment details');
    $response->assertSee('Graph create failed');
});
