import unittest

import pytest

from pypos.modules.dashboard.services.dashboard_value_utils import DashboardValueUtils

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


class DashboardValueUtilsTests(unittest.TestCase):
    def test_safe_number_parsers(self):
        self.assertEqual(DashboardValueUtils.safe_int("12", 0), 12)
        self.assertEqual(DashboardValueUtils.safe_int("x", 9), 9)
        self.assertEqual(DashboardValueUtils.to_non_negative_int("-1", 5), 5)
        self.assertAlmostEqual(DashboardValueUtils.safe_float("Rp 12.500,75", 0.0), 12500.75, places=2)

    def test_formatters(self):
        self.assertEqual(DashboardValueUtils.format_int_local(12500), "12.500")
        self.assertEqual(DashboardValueUtils.format_rupiah_local("12500"), "Rp 12.500")
        self.assertEqual(DashboardValueUtils.friendly_sync_table_name("price"), "Harga Jual")
        self.assertEqual(DashboardValueUtils.friendly_sync_table_name(""), "Data Master")

    def test_extract_changed_tables_and_total(self):
        payload = {
            "data": {
                "price": {
                    "row": 2,
                    "samples": [
                        {"entity_name": "Produk A", "before": 1000, "after": 1200},
                        {"entity_name": "Produk B", "before": 2000, "after": 2200},
                    ],
                },
                "diskon": {"row": 1},
            },
            "row": 3,
        }
        tables = DashboardValueUtils.extract_changed_tables_from_check(payload, requested_tables=["price", "diskon"])
        self.assertEqual(len(tables), 2)
        self.assertEqual(tables[0]["table"], "price")
        self.assertEqual(DashboardValueUtils.extract_row_total_from_check(payload, tables), 3)

    def test_signature_and_prompt_are_stable(self):
        changed_tables = [
            {
                "table": "price",
                "rows": 2,
                "samples": [
                    {"entity_name": "Produk A", "entity_id": "1", "changed_field": "harga_jual", "before_value": 1000, "after_value": 1200}
                ],
            }
        ]
        sig1 = DashboardValueUtils.build_auto_sync_update_signature(2, changed_tables)
        sig2 = DashboardValueUtils.build_auto_sync_update_signature(2, changed_tables)
        self.assertEqual(sig1, sig2)

        msg = DashboardValueUtils.build_auto_sync_prompt_message(2, changed_tables)
        self.assertIn("Ada perubahan pada produk", msg)
        self.assertIn("Produk A", msg)


if __name__ == "__main__":
    unittest.main()
