"""records_api_register: list API can trigger exchange pnl sync."""

from __future__ import annotations

import unittest
from unittest.mock import MagicMock

from flask import Flask

from lib.instance.records_api_register import register_trade_records_api


class RecordsApiSyncHookTest(unittest.TestCase):
    def test_list_calls_sync_hook(self):
        app = Flask(__name__)
        sync_calls = []

        def _login(fn):
            return fn

        def _get_db():
            conn = MagicMock()
            conn.execute.return_value.fetchall.return_value = []
            return conn

        def _win():
            return {"start_utc": None, "end_utc": None}

        register_trade_records_api(
            app,
            login_required=_login,
            get_db=_get_db,
            list_window_from_request=_win,
            utc_window_to_bj_sql_strings=lambda *a, **k: ("2026-01-01", "2026-12-31"),
            sql_list_time_field=lambda *a, **k: "COALESCE(closed_at, created_at, opened_at)",
            to_effective_trade_dict=lambda r: dict(r) if hasattr(r, "keys") else r,
            filter_trade_records_excluding_miss=lambda xs: xs,
            app_tz=None,
            sync_exchange_pnl_fn=lambda conn: sync_calls.append(conn),
        )
        client = app.test_client()
        resp = client.get("/api/trade_records")
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(len(sync_calls), 1)
        body = resp.get_json()
        self.assertTrue(body.get("ok"))


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