"""
ERP 交易域 Pydantic V2 Schemas
订单创建（嵌套明细）/ 详情响应 / 动态定价
"""

from __future__ import annotations

import uuid
from datetime import date, datetime

from pydantic import BaseModel, Field


# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# B2B 动态定价
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
class PriceCalculateRequest(BaseModel):
    customer_id: uuid.UUID
    sku_id: uuid.UUID


class PriceCalculateResponse(BaseModel):
    sku_id: uuid.UUID
    sku_code: str
    sku_name: str
    unit_price: float
    price_source: str  # "history" | "standard"
    last_order_no: str | None = None
    last_order_date: date | None = None


# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# 订单创建（嵌套明细）
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
class OrderItemCreate(BaseModel):
    sku_id: uuid.UUID
    qty: float = Field(..., gt=0, description="订购数量")
    unit_price: float = Field(..., ge=0, description="成交单价")


class OrderCreate(BaseModel):
    customer_id: uuid.UUID
    remark: str | None = None
    order_date: date | None = None
    items: list[OrderItemCreate] = Field(..., min_length=1, description="至少一个明细行")


# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# 订单明细响应
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
class OrderItemResponse(BaseModel):
    id: uuid.UUID
    sku_id: uuid.UUID
    sku_code: str | None = None
    sku_name: str | None = None
    spec: str | None = None
    qty: float
    unit_price: float
    sub_total: float
    shipped_qty: float = 0

    model_config = {"from_attributes": True}


# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# 订单主表响应
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
class OrderResponse(BaseModel):
    id: uuid.UUID
    order_no: str
    customer_id: uuid.UUID
    customer_name: str | None = None
    salesperson_id: uuid.UUID | None = None
    salesperson_name: str | None = None
    total_amount: float
    shipping_state: str
    payment_state: str
    paid_amount: float = 0
    remark: str | None = None
    order_date: date
    items: list[OrderItemResponse] = Field(default_factory=list)
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# 订单列表（不含 items 明细，减少传输体积）
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
class OrderBriefResponse(BaseModel):
    id: uuid.UUID
    order_no: str
    customer_id: uuid.UUID
    customer_name: str | None = None
    salesperson_name: str | None = None
    total_amount: float
    shipping_state: str
    payment_state: str
    paid_amount: float = 0
    order_date: date
    created_at: datetime

    model_config = {"from_attributes": True}


class OrderListResponse(BaseModel):
    total: int
    items: list[OrderBriefResponse]
    page: int
    size: int
