import json
import threading

import pytest

from pypos.core.utils import config_utils, db_helper


# edited by glg
pytestmark = [pytest.mark.unit]


def test_db_destructive_policy_non_strict_blocked_when_disabled(monkeypatch):
    monkeypatch.setattr(
        db_helper,
        "read_app_settings",
        lambda: {
            "maintenance_destructive_db_ops_enabled": 0,
            "maintenance_destructive_db_ops_allow_non_strict": 0,
            "maintenance_destructive_db_ops_reason": "",
        },
    )
    assert db_helper._enforce_destructive_policy("unit_test", strict=False) is False


def test_db_destructive_policy_strict_raise_when_disabled(monkeypatch):
    monkeypatch.setattr(
        db_helper,
        "read_app_settings",
        lambda: {
            "maintenance_destructive_db_ops_enabled": 0,
            "maintenance_destructive_db_ops_allow_non_strict": 0,
            "maintenance_destructive_db_ops_reason": "",
        },
    )
    with pytest.raises(PermissionError):
        db_helper._enforce_destructive_policy("unit_test", strict=True)


def test_db_destructive_policy_strict_allowed_when_enabled(monkeypatch):
    monkeypatch.setattr(
        db_helper,
        "read_app_settings",
        lambda: {
            "maintenance_destructive_db_ops_enabled": 1,
            "maintenance_destructive_db_ops_allow_non_strict": 0,
            "maintenance_destructive_db_ops_reason": "ops-window",
        },
    )
    assert db_helper._enforce_destructive_policy("unit_test", strict=True) is True


def test_config_cache_read_threadsafe(tmp_path, monkeypatch):
    config_file = tmp_path / "config.json"
    app_settings_file = tmp_path / "app_settings.json"
    config_file.write_text(json.dumps({"api_base_url": "https://example.test"}), encoding="utf-8")
    app_settings_file.write_text(json.dumps({"db_path": "db/test.db"}), encoding="utf-8")

    monkeypatch.setattr(config_utils, "CONFIG_FILE", str(config_file))
    monkeypatch.setattr(config_utils, "APP_SETTINGS_FILE", str(app_settings_file))
    config_utils.reload_config()

    errors = []
    results = []
    lock = threading.Lock()

    def _runner():
        try:
            cfg = config_utils.read_config()
            with lock:
                results.append(cfg)
        except Exception as exc:  # pragma: no cover - harus kosong
            with lock:
                errors.append(exc)

    threads = [threading.Thread(target=_runner) for _ in range(24)]
    for t in threads:
        t.start()
    for t in threads:
        t.join(timeout=3.0)

    assert not errors
    assert len(results) == 24
    assert all(isinstance(item, dict) for item in results)
    assert all(item.get("api_base_url") == "https://example.test" for item in results)
