"""
ERP 物流发货路由 —— /api/shipping
薄路由层：参数解析 + 调用 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.shipping import ShippingCreate
from app.schemas.response import ok
from app.services import shipping_service as svc

router = APIRouter(prefix="/shipping", tags=["物流发货"])


@router.post("", summary="执行分批发货（五步原子事务）")
async def create_shipping(
    body: ShippingCreate,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserPayload = Depends(get_current_user),
) -> dict:
    resp, new_state = await svc.create_shipping(db, current_user, body)
    return ok(data=resp.model_dump(mode="json"), message=f"发货单 {resp.shipping_no} 创建成功，订单状态已更新为 {new_state}")


@router.get("", summary="发货单大盘列表（数据权限与订单一致）")
async def list_shipping(
    page: int = Query(1, ge=1),
    size: int = Query(20, ge=1, le=100),
    order_no: str | None = Query(None, description="按订单号模糊搜索"),
    tracking_no: str | None = Query(None, description="按物流单号搜索"),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserPayload = Depends(get_current_user),
) -> dict:
    result = await svc.list_shipping(db, current_user, page, size, order_no, tracking_no)
    return ok(data=result.model_dump(mode="json"))


@router.get("/order/{order_id}", summary="查询特定订单的全部发货轨迹")
async def get_shipping_by_order(
    order_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserPayload = Depends(get_current_user),
) -> dict:
    result = await svc.get_shipping_by_order(db, current_user, order_id)
    return ok(data=result)
