# edited by glg
from pypos.modules.penjualan.services.transaksi_row_index_service import (
    TransaksiRowIndexService,
)


class _Cell:
    def __init__(self, text):
        self._text = str(text)

    def text(self):
        return self._text


class _Table:
    def __init__(self, rows):
        self._rows = list(rows or [])

    def rowCount(self):
        return len(self._rows)

    def item(self, row, col):
        if row < 0 or row >= len(self._rows):
            return None
        data = self._rows[row]
        if col == 0:
            return _Cell(data["pid"])
        if col == 4:
            return _Cell(data["qty"])
        return None

    def remove_row(self, idx):
        self._rows.pop(idx)


def _parse_qty(text):
    try:
        return int(str(text or "").strip())
    except Exception:
        return 0


def test_rebuild_and_find_row_reads_qty():
    table = _Table(
        [
            {"pid": "P1", "qty": "2"},
            {"pid": "P2", "qty": "5"},
        ]
    )
    svc = TransaksiRowIndexService(parse_qty_callback=_parse_qty)
    svc.rebuild(table)

    row, qty = svc.find_row(table, "P2")
    assert row == 1
    assert qty == 5


def test_shift_after_remove_keeps_mapping_consistent():
    table = _Table(
        [{"pid": f"P{i}", "qty": "1"} for i in range(40)]
    )
    svc = TransaksiRowIndexService(parse_qty_callback=_parse_qty)
    svc.rebuild(table)

    table.remove_row(10)
    svc.shift_after_remove(10, "P10")

    row, _ = svc.find_row(table, "P11")
    assert row == 10
    row_removed, _ = svc.find_row(table, "P10")
    assert row_removed is None


def test_find_row_repairs_stale_index_cache():
    table = _Table(
        [
            {"pid": "P100", "qty": "1"},
            {"pid": "P200", "qty": "3"},
        ]
    )
    svc = TransaksiRowIndexService(parse_qty_callback=_parse_qty)
    svc.register("P200", 5)  # cache stale sengaja

    row, qty = svc.find_row(table, "P200")
    assert row == 1
    assert qty == 3
