# edited by glg
from types import SimpleNamespace

import pytest

from pypos.modules.printer.services import printer_io_service

pytestmark = [pytest.mark.unit]


def test_test_connection_gagal_saat_dependency_escpos_tidak_tersedia(monkeypatch):
    monkeypatch.setattr(printer_io_service, "ESCPOS_PRINTER_AVAILABLE", False)
    svc = printer_io_service.PrinterIOService()
    status, code = svc.test_connection("lan", "127.0.0.1:9100")
    assert status is False
    assert code == "ERR_DEPENDENCY_MISSING"


def test_test_connection_tipe_koneksi_tidak_dikenal(monkeypatch):
    monkeypatch.setattr(printer_io_service, "ESCPOS_PRINTER_AVAILABLE", True)
    svc = printer_io_service.PrinterIOService()
    status, code = svc.test_connection("bluetooth", "AA:BB")
    assert status is False
    assert code == "ERR_CONN_TYPE_UNSUPPORTED"


def test_test_connection_lan_format_invalid(monkeypatch):
    monkeypatch.setattr(printer_io_service, "ESCPOS_PRINTER_AVAILABLE", True)
    svc = printer_io_service.PrinterIOService()
    status, code = svc.test_connection("lan", "invalid-format")
    assert status is False
    assert code == "ERR_FORMAT_LAN"


def test_test_connection_usb_backend_missing(monkeypatch):
    def _raise_no_backend(**_kwargs):
        raise Exception("No backend available")

    dummy_usb = SimpleNamespace(core=SimpleNamespace(find=_raise_no_backend))
    monkeypatch.setattr(printer_io_service, "ESCPOS_PRINTER_AVAILABLE", True)
    monkeypatch.setattr(printer_io_service, "USB_CORE_AVAILABLE", True)
    monkeypatch.setattr(printer_io_service, "usb", dummy_usb, raising=False)

    svc = printer_io_service.PrinterIOService()
    status, code = svc.test_connection("usb", "0x04b8:0x0202")
    assert status is False
    assert code == "ERR_USB_BACKEND_MISSING"
