"""Schemas for the advanced_order_editor plugin.

Pydantic v2 contracts only — services live in services.py, routes in router.py.
"""
from decimal import Decimal
from typing import Literal, Optional
from pydantic import BaseModel, Field, field_validator

AdjustmentKind = Literal["discount", "fee", "shipping"]


class AdjustmentIn(BaseModel):
    kind: AdjustmentKind
    label: str = Field(..., min_length=1, max_length=200)
    amount: Decimal = Field(..., gt=0, max_digits=12, decimal_places=2)
    note: Optional[str] = Field(None, max_length=500)

    @field_validator("label")
    @classmethod
    def _strip(cls, v: str) -> str:
        s = v.strip()
        if not s:
            raise ValueError("label must not be blank")
        return s


class AdvancedEditBody(BaseModel):
    # Reuses fields from the existing OrderEditBody plus adjustments[]
    status:            Optional[str]  = None
    note:              Optional[str]  = None
    carrier:           Optional[str]  = None
    tracking_no:       Optional[str]  = None
    estimated_delivery: Optional[str] = None
    shipping_address:  Optional[dict] = None
    items:             Optional[list] = None  # same shape as OrderEditItemBody
    adjustments:       list[AdjustmentIn] = Field(default_factory=list)
    # The `advanced` flag is implied by route; do NOT accept from client.


class AdvancedAdjustBody(BaseModel):
    mode: Literal["topup", "refund"]
    amount: Decimal = Field(..., gt=0, max_digits=12, decimal_places=2)
    idempotency_key: str = Field(..., min_length=8, max_length=120,
                                 description="Used as gateway_ref suffix for topup; logged on refund.")
    note: Optional[str] = Field(None, max_length=500)


class AdvancedAdjustOut(BaseModel):
    payment_id: Optional[int] = None
    refund_request_id: Optional[int] = None
    amount: Decimal
    mode: Literal["topup", "refund"]
    status: str  # pending for topup; pending for refund (RefReq is created pending)
