"""Trade models for ZenOTC SDK."""

from __future__ import annotations

from datetime import datetime
from decimal import Decimal
from enum import Enum
from typing import Any, Dict, Optional

from pydantic import Field

from zenotc.models.base import BaseModel, TimestampMixin


class TradeStatus(str, Enum):
    """Trade status."""

    PENDING = "pending"
    ESCROW_PENDING = "escrow_pending"
    ESCROW_FUNDED = "escrow_funded"
    PAYMENT_PENDING = "payment_pending"
    PAYMENT_SENT = "payment_sent"
    PAYMENT_CONFIRMED = "payment_confirmed"
    COMPLETED = "completed"
    CANCELLED = "cancelled"
    DISPUTED = "disputed"


class Trade(TimestampMixin):
    """Trade representation."""

    id: str = Field(..., description="Trade ID")
    order_id: str = Field(..., description="Associated order ID")
    buyer_id: str = Field(..., description="Buyer user ID")
    seller_id: str = Field(..., description="Seller user ID")
    asset: str = Field(..., description="Asset symbol")
    quantity: Decimal = Field(..., description="Trade quantity")
    price: Decimal = Field(..., description="Trade price")
    total_value: Decimal = Field(..., description="Total trade value")
    fee: Decimal = Field(default=Decimal("0"), description="Trading fee")
    status: TradeStatus = Field(..., description="Trade status")
    escrow_transaction_id: Optional[str] = Field(None, description="Escrow transaction ID")
    payment_reference: Optional[str] = Field(None, description="Payment reference")
    settlement_time: Optional[datetime] = Field(None, description="Settlement timestamp")
    completed_at: Optional[datetime] = Field(None, description="Completion timestamp")
    cancelled_at: Optional[datetime] = Field(None, description="Cancellation timestamp")
    cancellation_reason: Optional[str] = Field(None, description="Cancellation reason")
    metadata: Optional[Dict[str, Any]] = Field(None, description="Additional metadata")

    @property
    def is_active(self) -> bool:
        """Check if trade is active."""
        return self.status not in (
            TradeStatus.COMPLETED,
            TradeStatus.CANCELLED,
            TradeStatus.DISPUTED,
        )

    @property
    def is_complete(self) -> bool:
        """Check if trade is complete."""
        return self.status == TradeStatus.COMPLETED

    @property
    def net_value(self) -> Decimal:
        """Get net value after fees."""
        return self.total_value - self.fee
