from datetime import datetime
from enum import Enum
from sqlalchemy import String, DateTime, Integer, ForeignKey, JSON
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base


class AdminActionType(str, Enum):
    # User actions
    USER_BAN = "user_ban"
    USER_UNBAN = "user_unban"
    USER_AUTO_UNBAN = "user_auto_unban"  # System automatic unban
    USER_ROLE_CHANGE = "user_role_change"
    USER_PASSWORD_RESET = "user_password_reset"

    # Marathon actions
    MARATHON_FORCE_FINISH = "marathon_force_finish"
    MARATHON_DELETE = "marathon_delete"

    # Content actions
    CONTENT_UPDATE = "content_update"

    # Broadcast actions
    BROADCAST_ALL = "broadcast_all"
    BROADCAST_MARATHON = "broadcast_marathon"

    # Auth actions
    ADMIN_LOGIN = "admin_login"
    ADMIN_2FA_SUCCESS = "admin_2fa_success"
    ADMIN_2FA_FAIL = "admin_2fa_fail"


class AdminLog(Base):
    __tablename__ = "admin_logs"

    id: Mapped[int] = mapped_column(primary_key=True)
    admin_id: Mapped[int | None] = mapped_column(Integer, ForeignKey("users.id"), nullable=True, index=True)  # Nullable for system actions
    action: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
    target_type: Mapped[str] = mapped_column(String(50), nullable=False)
    target_id: Mapped[int] = mapped_column(Integer, nullable=False)
    details: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    ip_address: Mapped[str | None] = mapped_column(String(50), nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, index=True)

    # Relationships
    admin: Mapped["User"] = relationship("User", foreign_keys=[admin_id])
