"""MySQL 数据库操作工具 — 测试中的数据库校验/数据修改。

Usage:
    from tests.utils.db_helper import update_risk_control_status

    affected = update_risk_control_status("RHJC040026071600021457570057", status=1)
"""

import pymysql

DEFAULT_DB_CONFIG = {
    "host": "36.137.133.24",
    "port": 3306,
    "user": "ntocc",
    "password": "Rgxi3!kD9jjXpgzx",
    "database": "ntocc",
    "charset": "utf8mb4",
}


def get_connection(config: dict | None = None):
    """获取数据库连接。"""
    cfg = config or DEFAULT_DB_CONFIG
    return pymysql.connect(**cfg)


def execute_sql(sql: str, params: tuple | None = None, config: dict | None = None) -> int:
    """执行 SQL（INSERT/UPDATE/DELETE），返回影响行数。"""
    conn = get_connection(config)
    try:
        with conn.cursor() as cursor:
            affected = cursor.execute(sql, params)
            conn.commit()
            return affected
    finally:
        conn.close()


def query_sql(sql: str, params: tuple | None = None, config: dict | None = None) -> list[dict]:
    """执行查询 SQL，返回结果列表。"""
    conn = get_connection(config)
    try:
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute(sql, params)
            return cursor.fetchall()
    finally:
        conn.close()


def update_risk_control_status(order_code: str, status: int = 1, config: dict | None = None) -> int:
    """更新运单风控状态。

    执行 SQL:
        UPDATE tms_order_detail_ext SET risk_control_status = <status>
        WHERE order_detail_code IN (
            SELECT `code` FROM `tms_order_detail` WHERE order_code = '<order_code>'
        )

    Args:
        order_code: 运输单号（对应 tms_order_detail.order_code）
        status: 风控状态值，默认 1
        config: 数据库连接配置
    Returns:
        影响行数
    """
    sql = (
        "UPDATE tms_order_detail_ext SET risk_control_status = %s "
        "WHERE order_detail_code IN ("
        "  SELECT `code` FROM `tms_order_detail` WHERE order_code = %s"
        ")"
    )
    return execute_sql(sql, (status, order_code), config)
