<?php

// Feature: wallet-logs-and-settings, Property: getWalletSetting unit tests

declare(strict_types=1);

namespace Tests;

use PHPUnit\Framework\TestCase;

require_once __DIR__ . '/../includes/wallet_helpers.php';

/**
 * Task 1.4 — Unit tests for getWalletSetting().
 * Validates: Requirements 8.3, 9.3
 */
class WalletHelperTest extends TestCase
{
    private \mysqli $con;

    protected function setUp(): void
    {
        $host = defined('DB_SERVER') ? DB_SERVER : 'localhost';
        $user = defined('DB_USER')   ? DB_USER   : 'root';
        $pass = defined('DB_PASS')   ? DB_PASS   : '';
        $name = defined('DB_NAME')   ? DB_NAME   : 'sms';

        $this->con = new \mysqli($host, $user, $pass, $name);

        if ($this->con->connect_error) {
            $this->markTestSkipped('Cannot connect to DB: ' . $this->con->connect_error);
        }

        $this->con->query(
            "INSERT INTO wallet_settings (setting_key, setting_value, label)
             VALUES ('test_key_phpunit', 'test_value_42', 'Test')
             ON DUPLICATE KEY UPDATE setting_value = 'test_value_42'"
        );
    }

    protected function tearDown(): void
    {
        $this->con->query("DELETE FROM wallet_settings WHERE setting_key = 'test_key_phpunit'");
        $this->con->close();
    }

    public function testKeyExistsReturnsStoredValue(): void
    {
        $result = getWalletSetting($this->con, 'test_key_phpunit');
        $this->assertSame('test_value_42', $result);
    }

    public function testAbsentKeyReturnsProvidedDefault(): void
    {
        $result = getWalletSetting($this->con, 'nonexistent_key_xyz', 'my_default');
        $this->assertSame('my_default', $result);
    }

    public function testAbsentKeyNoDefaultReturnsNull(): void
    {
        $result = getWalletSetting($this->con, 'nonexistent_key_xyz');
        $this->assertNull($result);
    }
}
