<?php

declare(strict_types=1);

use App\Models\AuditLog;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Models\StoredReport;
use App\Models\ManagedEnvironment;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
use App\Support\Providers\ProviderReasonCodes;
use App\Support\Providers\ProviderVerificationStatus;
use App\Support\RedactionIntegrity;
use App\Support\SupportDiagnostics\SupportDiagnosticBundleBuilder;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('includes translated provider reasons and explicit support diagnostic redaction markers', function (): void {
    $tenant = ManagedEnvironment::factory()->create(['name' => 'Redaction ManagedEnvironment']);

    ProviderConnection::factory()
        ->withCredential()
        ->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'workspace_id' => (int) $tenant->workspace_id,
            'display_name' => 'Redaction connection',
            'verification_status' => ProviderVerificationStatus::Blocked->value,
            'last_error_reason_code' => ProviderReasonCodes::ProviderPermissionMissing,
            'last_error_message' => 'provider-secret-message',
            'last_health_check_at' => now()->subMinutes(15),
        ]);

    $bundle = app(SupportDiagnosticBundleBuilder::class)->forTenant($tenant);
    $providerSection = collect($bundle['sections'])->firstWhere('key', 'provider_connection');

    expect($bundle['redaction_mode'])->toBe('default_redacted')
        ->and($bundle['summary']['redaction_note'])->toBe(RedactionIntegrity::supportDiagnosticsNote())
        ->and($providerSection['summary'])->toContain('provider app is missing required Microsoft Graph permissions')
        ->and(collect($bundle['redaction']['markers'])->pluck('path')->all())
            ->toContain('provider_connection.credential', 'stored_reports.payload', 'audit_logs.metadata.raw')
        ->and(collect($providerSection['redaction_markers'])->pluck('path')->all())
            ->toContain('provider_connection.credential');
});

it('excludes raw provider payloads and unrestricted log excerpts from support bundles', function (): void {
    $tenant = ManagedEnvironment::factory()->create(['name' => 'Secret-Free ManagedEnvironment']);

    $connection = ProviderConnection::factory()
        ->withCredential()
        ->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'workspace_id' => (int) $tenant->workspace_id,
            'verification_status' => ProviderVerificationStatus::Blocked->value,
            'last_error_reason_code' => ProviderReasonCodes::ProviderPermissionMissing,
            'last_error_message' => 'raw-provider-secret-message',
        ]);

    $run = OperationRun::factory()
        ->forTenant($tenant)
        ->create([
            'type' => OperationRunType::BaselineCompare->value,
            'status' => OperationRunStatus::Completed->value,
            'outcome' => OperationRunOutcome::Failed->value,
            'context' => [
                'provider_connection_id' => (int) $connection->getKey(),
                'raw_response_body' => 'secret-provider-body',
            ],
            'summary_counts' => [
                'total' => 0,
                'processed' => 0,
            ],
            'completed_at' => now()->subMinutes(10),
        ]);

    StoredReport::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'report_type' => StoredReport::REPORT_TYPE_PERMISSION_POSTURE,
        'payload' => [
            'raw_response_body' => 'stored-report-secret-body',
        ],
    ]);

    AuditLog::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'operation_run_id' => (int) $run->getKey(),
        'action' => 'operation.failed',
        'resource_type' => 'operation_run',
        'resource_id' => (string) $run->getKey(),
        'target_label' => 'Operation #'.$run->getKey(),
        'metadata' => [
            'raw_response_body' => 'audit-secret-body',
        ],
        'outcome' => 'success',
        'recorded_at' => now()->subMinutes(5),
    ]);

    $bundleJson = json_encode(app(SupportDiagnosticBundleBuilder::class)->forOperationRun($run), JSON_THROW_ON_ERROR);

    expect($bundleJson)
        ->not->toContain('raw-provider-secret-message')
        ->not->toContain('secret-provider-body')
        ->not->toContain('stored-report-secret-body')
        ->not->toContain('audit-secret-body')
        ->toContain('default_redacted')
        ->toContain('[REDACTED]');
});