from datetime import datetime

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

from app.models.base import BaseModel


class UpstreamActionLog(BaseModel):
    """Audit trail for high-risk upstream resource operations."""

    __tablename__ = "upstream_action_logs"

    user_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, index=True)
    order_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
    order_refund_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
    instance_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
    cloud_server_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
    upstream_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)

    action_type: Mapped[str] = mapped_column(
        String(48), nullable=False, index=True, comment="instance_delete / disk_delete / suspend ..."
    )
    resource_type: Mapped[str] = mapped_column(
        String(32), nullable=False, index=True, comment="instance / disk / package / bandwidth"
    )
    resource_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    source: Mapped[str] = mapped_column(
        String(32), nullable=False, index=True, comment="manual / unsubscribe / lifecycle / renewal"
    )
    status: Mapped[str] = mapped_column(
        String(24), nullable=False, default="submitted", index=True,
        comment="submitted / running / success / failed / no_task / manual_handled / ignored / superseded",
    )

    upstream_task_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
    request_method: Mapped[str | None] = mapped_column(String(8), nullable=True)
    request_path: Mapped[str | None] = mapped_column(String(255), nullable=True)
    request_payload: Mapped[dict | list | None] = mapped_column(JSON, nullable=True)
    response_payload: Mapped[dict | list | None] = mapped_column(JSON, nullable=True)
    task_payload: Mapped[dict | list | None] = mapped_column(JSON, nullable=True)
    error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
    remark: Mapped[str | None] = mapped_column(Text, nullable=True)

    attempt_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    last_checked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
