from datetime import datetime

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

from app.models.base import BaseModel


class OrderRefund(BaseModel):
    """User service unsubscribe/refund audit record."""

    __tablename__ = "order_refunds"

    refund_no: Mapped[str] = mapped_column(String(64), unique=True, nullable=False, index=True)
    user_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
    )
    order_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("orders.id", ondelete="CASCADE"), nullable=False, index=True
    )
    refund_type: Mapped[str] = mapped_column(
        String(24), nullable=False, index=True, comment="full / prorated / no_refund"
    )
    refund_amount: Mapped[int] = mapped_column(Integer, default=0, nullable=False, comment="Refund amount in cents")
    status: Mapped[str] = mapped_column(String(24), default="success", nullable=False, index=True)
    resource_status: Mapped[str] = mapped_column(
        String(24),
        default="none",
        nullable=False,
        index=True,
        comment="none / running / failed / finished / manual_handled / ignored",
    )
    resource_error: Mapped[str | None] = mapped_column(Text, nullable=True)
    resource_completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    reason: Mapped[str | None] = mapped_column(Text, nullable=True)
    payload_snapshot: Mapped[dict | None] = mapped_column(JSON, nullable=True)
