from datetime import datetime

from sqlalchemy import BigInteger, DateTime, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column

from app.models.base import BaseModel


class AgentSettlement(BaseModel):
    """Agent/member settlement ledger for service orders."""

    __tablename__ = "agent_settlements"

    order_id: Mapped[int] = mapped_column(
        Integer, nullable=False, index=True, comment="Related order id",
    )
    order_no: Mapped[str] = mapped_column(
        String(64), nullable=False, comment="Order number snapshot",
    )
    settlement_type: Mapped[str] = mapped_column(
        String(32), nullable=False, index=True,
        comment="agent_profit / agent_subsidy / member_commission",
    )
    user_id: Mapped[int] = mapped_column(
        BigInteger, nullable=False, index=True, comment="Settlement owner user id",
    )
    customer_user_id: Mapped[int | None] = mapped_column(
        BigInteger, nullable=True, comment="Customer user id",
    )
    agent_tier_id: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="Agent tier snapshot id",
    )
    standard_amount: Mapped[int] = mapped_column(
        Integer, default=0, nullable=False, comment="Standard amount in cents",
    )
    customer_pay_amount: Mapped[int] = mapped_column(
        Integer, default=0, nullable=False, comment="Customer paid amount in cents",
    )
    agent_cost_rate: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="Agent cost rate in basis points",
    )
    agent_cost_amount: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="Agent cost amount in cents",
    )
    delta_amount: Mapped[int] = mapped_column(
        Integer, default=0, nullable=False, comment="Positive profit / negative subsidy in cents",
    )
    commission_rate: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="Member commission rate in basis points",
    )
    status: Mapped[str] = mapped_column(
        String(24), default="pending", nullable=False, index=True,
        comment="pending / frozen / settled / reversed",
    )
    frozen_until: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True, comment="Frozen reward release time",
    )
    points_amount: Mapped[int] = mapped_column(
        Integer, default=0, nullable=False, comment="Settlement points amount",
    )
    point_log_id: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="Credited point log id",
    )
    settled_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True, comment="Settlement time",
    )
    reversed_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True, comment="Reversed time",
    )
    remark: Mapped[str | None] = mapped_column(Text, nullable=True, comment="Remark")
