<?php

// Feature: wallet-logs-and-settings, Property 7: Settings form pre-populated from database values

declare(strict_types=1);

namespace Tests;

use PHPUnit\Framework\TestCase;

/**
 * Task 1.2 — Schema correctness and seed data verification.
 * Validates: Requirements 5.2
 */
class WalletSettingsSchemaTest extends TestCase
{
    private static \mysqli $con;

    public static function setUpBeforeClass(): 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';

        self::$con = new \mysqli($host, $user, $pass, $name);

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

        // Run the migration SQL
        $sqlFile = __DIR__ . '/../migrations/create_wallet_settings_tables.sql';
        $sql = file_get_contents($sqlFile);

        // Split on semicolons, skip empty/comment-only lines
        $statements = array_filter(
            array_map('trim', explode(';', $sql)),
            fn(string $s) => $s !== '' && !preg_match('/^\s*--/', $s)
        );

        foreach ($statements as $statement) {
            if (!self::$con->query($statement)) {
                self::fail('Migration failed on statement: ' . $statement . ' — ' . self::$con->error);
            }
        }
    }

    public static function tearDownAfterClass(): void
    {
        if (isset(self::$con) && self::$con instanceof \mysqli) {
            self::$con->close();
        }
    }

    public function testDefaultSeedRowsExist(): void
    {
        $expected = [
            'max_balance'      => '100000',
            'min_balance'      => '0',
            'funding_enabled'  => '1',
            'payments_enabled' => '1',
        ];

        $result = self::$con->query(
            "SELECT setting_key, setting_value FROM wallet_settings WHERE setting_key IN ('max_balance','min_balance','funding_enabled','payments_enabled')"
        );

        $this->assertNotFalse($result, 'Query on wallet_settings failed: ' . self::$con->error);

        $rows = [];
        while ($row = $result->fetch_assoc()) {
            $rows[$row['setting_key']] = $row['setting_value'];
        }

        foreach ($expected as $key => $value) {
            $this->assertArrayHasKey($key, $rows, "Missing seed key: {$key}");
            $this->assertSame($value, $rows[$key], "Unexpected value for {$key}");
        }
    }

    public function testWalletSettingsLogTableExists(): void
    {
        $result = self::$con->query("SHOW TABLES LIKE 'wallet_settings_log'");

        $this->assertNotFalse($result, 'SHOW TABLES query failed: ' . self::$con->error);
        $this->assertSame(1, $result->num_rows, "Table 'wallet_settings_log' does not exist");
    }
}
