"""
积分充值订单 CRUD
=================

支持按订单号、用户、状态查询。
"""

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.crud.base import CRUDBase
from app.models.point_recharge_order import PointRechargeOrder


class PointRechargeOrderCRUD(CRUDBase[PointRechargeOrder]):
    """积分充值订单数据访问对象"""

    def __init__(self) -> None:
        super().__init__(PointRechargeOrder)

    async def get_by_out_trade_no(
        self, db: AsyncSession, *, out_trade_no: str
    ) -> PointRechargeOrder | None:
        """根据商户订单号查询"""
        result = await db.execute(
            select(PointRechargeOrder).where(
                PointRechargeOrder.out_trade_no == out_trade_no
            )
        )
        return result.scalar_one_or_none()

    async def get_by_wx_order_no(
        self, db: AsyncSession, *, wx_order_no: str
    ) -> PointRechargeOrder | None:
        """根据微信支付订单号查询"""
        result = await db.execute(
            select(PointRechargeOrder).where(
                PointRechargeOrder.wx_order_no == wx_order_no
            )
        )
        return result.scalar_one_or_none()

    async def get_by_user_id(
        self,
        db: AsyncSession,
        *,
        user_id: str,
        skip: int = 0,
        limit: int = 20,
    ) -> list[PointRechargeOrder]:
        """根据用户 ID 查询充值记录（分页，按时间倒序）"""
        result = await db.execute(
            select(PointRechargeOrder)
            .where(PointRechargeOrder.user_id == user_id)
            .order_by(PointRechargeOrder.created_at.desc())
            .offset(skip)
            .limit(limit)
        )
        return list(result.scalars().all())

    async def get_pending_orders(
        self,
        db: AsyncSession,
        *,
        limit: int = 100,
    ) -> list[PointRechargeOrder]:
        """获取待支付的订单（用于定时清理超时订单）"""
        result = await db.execute(
            select(PointRechargeOrder)
            .where(PointRechargeOrder.status == "pending")
            .order_by(PointRechargeOrder.created_at.asc())
            .limit(limit)
        )
        return list(result.scalars().all())


# 导出实例
point_recharge_order = PointRechargeOrderCRUD()
