"""OrderMetadataDB 单元测试。"""
import unittest
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))

from app.core.db.order_metadata_db import OrderMetadataDB


class TestOrderMetadataDB(unittest.TestCase):
    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()
        self.db_path = str(Path(self.tmpdir) / "test_cache.db")
        self.db = OrderMetadataDB(self.db_path)

    def test_save_and_get(self):
        ok = self.db.save("hash001", supplier="永辉超市", bill_date="20260717",
                          total_amount=656.00, raw_supplier_text="永辉超市供货单")
        self.assertTrue(ok)
        row = self.db.get("hash001")
        self.assertIsNotNone(row)
        self.assertEqual(row["supplier"], "永辉超市")
        self.assertEqual(row["bill_date"], "20260717")
        self.assertAlmostEqual(row["total_amount"], 656.00)

    def test_upsert(self):
        self.db.save("hash001", supplier="永辉", bill_date="20260717", total_amount=100)
        self.db.save("hash001", supplier="永辉2", bill_date="20260718", total_amount=200)
        row = self.db.get("hash001")
        self.assertEqual(row["supplier"], "永辉2")
        self.assertEqual(row["bill_date"], "20260718")
        self.assertAlmostEqual(row["total_amount"], 200)

    def test_get_missing(self):
        self.assertIsNone(self.db.get("nonexistent"))

    def test_list_all(self):
        for i in range(3):
            self.db.save(f"hash{i}", supplier=f"s{i}")
        rows = self.db.list_all()
        self.assertEqual(len(rows), 3)

    def test_count(self):
        self.assertEqual(self.db.count(), 0)
        self.db.save("h1")
        self.db.save("h2")
        self.assertEqual(self.db.count(), 2)

    def test_empty_hash_skipped(self):
        self.assertFalse(self.db.save("", supplier="x"))

    def test_delete(self):
        self.db.save("h1")
        self.db.delete("h1")
        self.assertIsNone(self.db.get("h1"))


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