"""
ERP 订单管理路由 —— /api/orders
薄路由层：参数解析 + 调用 Service + 包装响应
"""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_current_user
from app.db.database import get_db
from app.schemas.auth import CurrentUserPayload
from app.schemas.order import OrderCreate
from app.schemas.response import ok
from app.services import order_service as svc

router = APIRouter(prefix="/orders", tags=["订单管理"])


@router.get("/price/calculate", summary="B2B 动态定价：历史成交价追溯 → 标准价兜底")
async def calculate_price(
    customer_id: uuid.UUID = Query(..., description="客户 ID"),
    sku_id: uuid.UUID = Query(..., description="产品 SKU ID"),
    db: AsyncSession = Depends(get_db),
    _: CurrentUserPayload = Depends(get_current_user),
) -> dict:
    result = await svc.calculate_price(db, customer_id, sku_id)
    return ok(data=result.model_dump(mode="json"))


@router.post("", summary="创建订单（主子表事务）")
async def create_order(
    body: OrderCreate,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserPayload = Depends(get_current_user),
) -> dict:
    result = await svc.create_order(db, current_user, body)
    return ok(data=result.model_dump(mode="json"), message=f"订单 {result.order_no} 创建成功")


@router.get("", summary="订单大盘列表（含数据权限隔离）")
async def list_orders(
    page: int = Query(1, ge=1),
    size: int = Query(20, ge=1, le=100),
    customer_id: uuid.UUID | None = Query(None),
    shipping_state: str | None = Query(None, pattern=r"^(pending|partial|shipped)$"),
    payment_state: str | None = Query(None, pattern=r"^(unpaid|partial|cleared)$"),
    keyword: str | None = Query(None, description="模糊搜索订单号"),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserPayload = Depends(get_current_user),
) -> dict:
    result = await svc.list_orders(db, current_user, page, size, customer_id, shipping_state, payment_state, keyword)
    return ok(data=result.model_dump(mode="json"))


@router.get("/{order_id}", summary="订单全景详情（关系预加载 items + customer）")
async def get_order(
    order_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserPayload = Depends(get_current_user),
) -> dict:
    result = await svc.get_order(db, current_user, order_id)
    return ok(data=result.model_dump(mode="json"))
