<?php
/**
 * Logger 测试
 *
 * @package StablePay_WooCommerce
 */

use PHPUnit\Framework\TestCase;

class LoggerTest extends TestCase {
    /**
     * 测试 Logger 初始化
     */
    public function test_logger_initialization() {
        $logger = new StablePay_Logger(true, StablePay_Logger::LEVEL_INFO);
        $this->assertInstanceOf(StablePay_Logger::class, $logger);
    }

    /**
     * 测试日志级别过滤
     */
    public function test_log_level_filtering() {
        $logger = new StablePay_Logger(true, StablePay_Logger::LEVEL_ERROR);

        // 使用反射测试私有方法
        $reflection = new ReflectionClass($logger);
        $method = $reflection->getMethod('should_log');
        $method->setAccessible(true);

        // ERROR 级别应该被记录
        $this->assertTrue($method->invoke($logger, StablePay_Logger::LEVEL_ERROR));

        // INFO 级别不应该被记录
        $this->assertFalse($method->invoke($logger, StablePay_Logger::LEVEL_INFO));
    }

    /**
     * 测试上下文脱敏
     */
    public function test_context_sanitization() {
        $logger = new StablePay_Logger(true, StablePay_Logger::LEVEL_INFO);

        $reflection = new ReflectionClass($logger);
        $method = $reflection->getMethod('sanitize_context');
        $method->setAccessible(true);

        $context = array(
            'api_key' => '1234567890abcdef',
            'order_id' => '12345',
        );

        $sanitized = $method->invoke($logger, $context);

        // API Key 应该被脱敏
        $this->assertStringContainsString('****', $sanitized['api_key']);
        $this->assertStringStartsWith('1234', $sanitized['api_key']);
        $this->assertStringEndsWith('cdef', $sanitized['api_key']);

        // 普通字段不应该被脱敏
        $this->assertEquals('12345', $sanitized['order_id']);
    }

    /**
     * 测试消息格式化
     */
    public function test_message_formatting() {
        $logger = new StablePay_Logger(true, StablePay_Logger::LEVEL_INFO);

        $reflection = new ReflectionClass($logger);
        $method = $reflection->getMethod('format_message');
        $method->setAccessible(true);

        // 无上下文
        $message = $method->invoke($logger, 'Test message', array());
        $this->assertEquals('Test message', $message);

        // 有上下文
        $message = $method->invoke($logger, 'Test message', array('key' => 'value'));
        $this->assertStringContainsString('Test message', $message);
        $this->assertStringContainsString('Context:', $message);
    }
}
