# edited by glg
import pytest

from pypos.modules.settings.services.printer_settings_service import PrinterSettingsService

pytestmark = [pytest.mark.unit]


class _FacadeStub:
    def __init__(self):
        self.calls = []

    def set_settlement_print_option(self, key, enabled):
        self.calls.append((str(key), bool(enabled)))
        return True


class _AdminAuthStub:
    def __init__(self, ok=True):
        self.ok = bool(ok)

    def validate_admin_credentials(self, username, password):
        _ = username
        _ = password
        if self.ok:
            return True, "ok", {"nama_login": "admin.test"}
        return False, "Admin/password salah.", {}


def test_update_settlement_print_option_invalid_key():
    service = PrinterSettingsService(
        printer_facade_service=_FacadeStub(),
        admin_auth_service=_AdminAuthStub(ok=True),
    )
    ok, message, payload = service.update_settlement_print_option(
        option_key="invalid_key",
        enabled=True,
        admin_username="admin",
        admin_password="pass",
    )
    assert ok is False
    assert "tidak valid" in str(message).lower()
    assert payload == {}


def test_update_settlement_print_option_auth_fail():
    facade = _FacadeStub()
    service = PrinterSettingsService(
        printer_facade_service=facade,
        admin_auth_service=_AdminAuthStub(ok=False),
    )
    ok, message, payload = service.update_settlement_print_option(
        option_key="show_cash_recap",
        enabled=True,
        admin_username="admin",
        admin_password="salah",
    )
    assert ok is False
    assert "gagal" in str(message).lower() or "salah" in str(message).lower()
    assert payload == {}
    assert facade.calls == []


def test_update_settlement_print_option_enabled_parse_deterministic():
    facade = _FacadeStub()
    service = PrinterSettingsService(
        printer_facade_service=facade,
        admin_auth_service=_AdminAuthStub(ok=True),
    )

    ok1, _msg1, out1 = service.update_settlement_print_option(
        option_key="show_transaction_list",
        enabled="0",
        admin_username="admin",
        admin_password="pass",
    )
    ok2, _msg2, out2 = service.update_settlement_print_option(
        option_key="show_transaction_list",
        enabled="yes",
        admin_username="admin",
        admin_password="pass",
    )

    assert ok1 is True
    assert ok2 is True
    assert out1.get("enabled") is False
    assert out2.get("enabled") is True
    assert facade.calls == [
        ("show_transaction_list", False),
        ("show_transaction_list", True),
    ]
