<?php

declare(strict_types=1);

use App\Filament\Resources\FindingResource;
use App\Filament\Resources\PolicyResource;
use App\Filament\Resources\PolicyVersionResource;
use App\Models\Finding;
use App\Models\InventoryItem;
use App\Models\Policy;
use App\Models\PolicyVersion;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('renders shared normalized settings and diff families on policy and policy-version detail hosts', function (): void {
    $tenant = \App\Models\ManagedEnvironment::factory()->create([
        'name' => 'ManagedEnvironment One',
        'status' => 'active',
    ]);

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

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

    PolicyVersion::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'policy_id' => $policy->getKey(),
        'version_number' => 1,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'created_by' => 'tester@example.com',
        'captured_at' => CarbonImmutable::now()->subMinute(),
        'snapshot' => [
            'displayName' => 'Policy A',
            'settings' => [
                ['displayName' => 'Enable feature', 'value' => ['value' => 'off']],
            ],
        ],
    ]);

    $version = PolicyVersion::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'policy_id' => $policy->getKey(),
        'version_number' => 2,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'created_by' => 'tester@example.com',
        'captured_at' => CarbonImmutable::now(),
        'snapshot' => [
            'displayName' => 'Policy A',
            'settings' => [
                ['displayName' => 'Enable feature', 'value' => ['value' => 'on']],
            ],
        ],
    ]);

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

    $policyResponse->assertSuccessful()->assertSee('Enable feature');

    expect($policyResponse->getContent())
        ->toContain('data-shared-detail-family="normalized-settings"')
        ->toContain('data-shared-normalized-settings-host="policy"');

    $versionResponse = $this->actingAs($user)
        ->get(PolicyVersionResource::getUrl('view', ['record' => $version], tenant: $tenant));

    $versionResponse->assertSuccessful()->assertSee('Normalized diff');

    expect($versionResponse->getContent())
        ->toContain('data-shared-detail-family="normalized-settings"')
        ->toContain('data-shared-normalized-settings-host="policy_version"')
        ->toContain('data-shared-detail-family="normalized-diff"')
        ->toContain('data-shared-normalized-diff-host="policy_version"');
});

it('renders the shared normalized diff family on finding detail hosts', function (): void {
    bindFailHardGraphClient();

    [$user, $tenant] = createUserWithTenant(role: 'manager');

    $baseline = createInventorySyncOperationRun($tenant, [
        'selection_hash' => hash('sha256', 'shared-detail-contract'),
        'status' => 'success',
        'finished_at' => now()->subDays(2),
    ]);

    $current = createInventorySyncOperationRun($tenant, [
        'selection_hash' => $baseline->selection_hash,
        'status' => 'success',
        'finished_at' => now()->subDay(),
    ]);

    $policy = Policy::factory()->for($tenant)->create([
        'external_id' => 'policy-123',
        'policy_type' => 'deviceConfiguration',
        'platform' => 'windows10',
    ]);

    $baselineVersion = PolicyVersion::factory()->for($tenant)->create([
        'policy_id' => $policy->getKey(),
        'version_number' => 1,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'captured_at' => $baseline->finished_at->copy()->subHour(),
        'snapshot' => [
            'displayName' => 'My Policy',
            'customSettingFoo' => 'Old value',
        ],
    ]);

    $currentVersion = PolicyVersion::factory()->for($tenant)->create([
        'policy_id' => $policy->getKey(),
        'version_number' => 2,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'captured_at' => $current->finished_at->copy()->subHour(),
        'snapshot' => [
            'displayName' => 'My Policy',
            'customSettingFoo' => 'New value',
        ],
    ]);

    $finding = Finding::factory()->for($tenant)->create([
        'finding_type' => Finding::FINDING_TYPE_DRIFT,
        'scope_key' => (string) $current->selection_hash,
        'baseline_operation_run_id' => $baseline->getKey(),
        'current_operation_run_id' => $current->getKey(),
        'subject_type' => 'policy',
        'subject_external_id' => $policy->external_id,
        'evidence_jsonb' => [
            'change_type' => 'modified',
            'summary' => [
                'kind' => 'policy_snapshot',
                'changed_fields' => ['snapshot_hash'],
            ],
            'baseline' => [
                'policy_id' => $policy->external_id,
                'policy_version_id' => $baselineVersion->getKey(),
                'snapshot_hash' => 'baseline-hash',
            ],
            'current' => [
                'policy_id' => $policy->external_id,
                'policy_version_id' => $currentVersion->getKey(),
                'snapshot_hash' => 'current-hash',
            ],
        ],
    ]);

    InventoryItem::factory()->for($tenant)->create([
        'external_id' => $finding->subject_external_id,
        'display_name' => 'My Policy 123',
    ]);

    $response = $this->actingAs($user)
        ->get(FindingResource::getUrl('view', ['record' => $finding], tenant: $tenant));

    $response->assertSuccessful()->assertSee('Normalized diff');

    expect($response->getContent())
        ->toContain('data-shared-detail-family="normalized-diff"')
        ->toContain('data-shared-normalized-diff-host="finding"');
});
