"""records_list_lib pagination."""

from __future__ import annotations

import sqlite3
import unittest

from lib.instance.records_list_lib import list_trade_records_page
from lib.trade.trade_result_lib import filter_trade_records_excluding_miss


def _to_effective(row):
    d = dict(row)
    d["effective_result"] = d.get("result")
    d["effective_pnl_amount"] = d.get("pnl_amount")
    return d


class RecordsListLibTest(unittest.TestCase):
    def setUp(self):
        self.conn = sqlite3.connect(":memory:")
        self.conn.row_factory = sqlite3.Row
        self.conn.execute(
            """
            CREATE TABLE trade_records (
                id INTEGER PRIMARY KEY,
                closed_at TEXT,
                created_at TEXT,
                opened_at TEXT,
                result TEXT,
                pnl_amount REAL
            )
            """
        )
        for i in range(12):
            self.conn.execute(
                "INSERT INTO trade_records(id, closed_at, created_at, opened_at, result, pnl_amount) "
                "VALUES (?,?,?,?,?,?)",
                (i + 1, f"2026-07-1{i % 9}-10:00:00", None, None, "止盈", 1.0),
            )
        self.conn.execute(
            "INSERT INTO trade_records(id, closed_at, created_at, opened_at, result, pnl_amount) "
            "VALUES (?,?,?,?,?,?)",
            (99, "2026-07-15-10:00:00", None, None, "错过", 0),
        )
        self.conn.commit()

    def tearDown(self):
        self.conn.close()

    def test_pages_exclude_miss(self):
        out = list_trade_records_page(
            self.conn,
            "2026-07-01",
            "2026-07-31",
            tr_ts="COALESCE(closed_at, created_at, opened_at)",
            to_effective_fn=_to_effective,
            filter_fn=filter_trade_records_excluding_miss,
            limit=5,
            offset=0,
        )
        self.assertTrue(out["ok"])
        self.assertEqual(out["total"], 12)
        self.assertEqual(out["pages"], 3)
        self.assertEqual(len(out["items"]), 5)

    def test_second_page(self):
        out = list_trade_records_page(
            self.conn,
            "2026-07-01",
            "2026-07-31",
            tr_ts="COALESCE(closed_at, created_at, opened_at)",
            to_effective_fn=_to_effective,
            filter_fn=filter_trade_records_excluding_miss,
            limit=5,
            offset=5,
        )
        self.assertEqual(out["page"], 2)
        self.assertEqual(len(out["items"]), 5)


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