<?php

namespace MintyPHP\Tests\Architecture;

use PHPUnit\Framework\TestCase;

final class SecurityLoggingRuntimeContractTest extends TestCase
{
    use ProjectFileAssertionSupport;

    public function testFrontendTelemetryIngestUsesOnlyRequestScopedErrorLogFallback(): void
    {
        $violations = array_merge(
            $this->findPatternMatchesInPhpFiles('core', '/\berror_log\s*\(/'),
            $this->findPatternMatchesInPhpFiles('pages', '/\berror_log\s*\(/'),
            $this->findPatternMatchesInPhpFiles('modules', '/\berror_log\s*\(/')
        );
        sort($violations);

        self::assertSame(
            ['modules/audit/pages/audit/frontend-telemetry/ingest().php'],
            $violations,
            "Unexpected error_log() usage outside the telemetry ingest fallback:\n" . implode("\n", $violations)
        );

        $content = $this->readProjectFile('modules/audit/pages/audit/frontend-telemetry/ingest().php');
        self::assertStringContainsString(
            "error_log('[frontend-telemetry] ingest record_failed request_id=' . RequestContext::id());",
            $content
        );

        preg_match('/^.*\berror_log\s*\(.*$/m', $content, $matches);
        $errorLogLine = $matches[0] ?? '';

        self::assertNotSame('', $errorLogLine, 'Expected a dedicated telemetry error_log() fallback line.');
        self::assertStringNotContainsString('$payload', $errorLogLine);
        self::assertStringNotContainsString('$record', $errorLogLine);
        self::assertStringNotContainsString('$events', $errorLogLine);
    }
}
