<?php

declare(strict_types=1);

use App\Models\Finding;
use App\Models\InventoryItem;
use App\Models\StoredReport;
use App\Support\Ai\AiUseCaseCatalog;
use App\Support\Artifacts\ArtifactSourceDescriptor;
use App\Support\Artifacts\ArtifactSourceTaxonomy;

it('keeps provider-native type names out of descriptor top-level truth', function (): void {
    [$user, $tenant] = createUserWithTenant();

    $finding = Finding::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'evidence_jsonb' => ['policy_type' => 'deviceCompliancePolicy'],
    ]);
    $report = StoredReport::factory()->permissionPosture()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
    ]);
    $inventory = InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'policy_type' => 'deviceCompliancePolicy',
    ]);

    foreach ([$finding->artifactSourceDescriptor(), $report->artifactSourceDescriptor(), $inventory->artifactSourceDescriptor()] as $descriptor) {
        $payload = $descriptor->toArray();

        expect($payload)->not->toHaveKeys(['finding_type', 'report_type', 'policy_type'])
            ->and($payload['package_run_id'])->toBeNull();
    }

    expect($finding->artifactProviderDetail()->toArray()['legacy_policy_type'])->toBe('deviceCompliancePolicy')
        ->and($report->artifactProviderDetail()->toArray()['legacy_report_type'])->toBe(StoredReport::REPORT_TYPE_PERMISSION_POSTURE)
        ->and($inventory->artifactProviderDetail()->toArray()['legacy_policy_type'])->toBe('deviceCompliancePolicy');

    $this->actingAs($user);
});

it('keeps package_run_id optional and does not recast AI source families as artifact runtime truth', function (): void {
    $descriptor = ArtifactSourceDescriptor::fromArray([
        'workspace_id' => 1,
        'tenant_id' => 2,
        'managed_environment_id' => 2,
        'source_family' => 'finding',
        'source_kind' => 'model_summary',
        'provider_key' => 'microsoft',
        'source_target_kind' => 'managed_environment',
        'package_run_id' => 123,
    ]);

    $aiSourceFamilies = collect(app(AiUseCaseCatalog::class)->all())->pluck('source_family');

    expect($descriptor->packageRunId)->toBe(123)
        ->and($aiSourceFamilies->intersect(ArtifactSourceTaxonomy::sourceFamilies())->values()->all())->toBe([])
        ->and($aiSourceFamilies->all())->toContain('product_knowledge', 'support_diagnostics');
});
