"""注册 /api/trade_records(三所共用)."""

from __future__ import annotations

from typing import Any, Callable

from flask import Flask, jsonify, request


def register_trade_records_api(
    app: Flask,
    *,
    login_required: Callable,
    get_db: Callable,
    list_window_from_request: Callable[[], dict[str, Any]],
    utc_window_to_bj_sql_strings: Callable[..., tuple[str, str]],
    sql_list_time_field: Callable[..., str],
    to_effective_trade_dict: Callable[[Any], dict[str, Any]],
    filter_trade_records_excluding_miss: Callable[[list], list],
    app_tz: Any,
) -> None:
    from lib.instance.records_list_lib import list_trade_records_page

    @app.route("/api/trade_records")
    @login_required
    def api_trade_records():
        win = list_window_from_request()
        start_bj, end_bj = utc_window_to_bj_sql_strings(
            win["start_utc"], win["end_utc"], app_tz
        )
        tr_ts = sql_list_time_field("closed_at", "created_at", "opened_at")
        try:
            limit = int(request.args.get("limit") or 5)
        except (TypeError, ValueError):
            limit = 5
        try:
            offset = int(request.args.get("offset") or 0)
        except (TypeError, ValueError):
            offset = 0
        conn = get_db()
        try:
            payload = list_trade_records_page(
                conn,
                start_bj,
                end_bj,
                tr_ts=tr_ts,
                to_effective_fn=to_effective_trade_dict,
                filter_fn=filter_trade_records_excluding_miss,
                limit=limit,
                offset=offset,
            )
            return jsonify(payload)
        finally:
            conn.close()
