from datetime import datetime

from sqlalchemy import DateTime, Index, Integer, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column

from app.db import Base


class LoginThrottle(Base):
    """Tracks per-key login failure state for exponential back-off throttling.

    ``scope`` is either ``'ip'`` or ``'user'``; ``key`` is the IP address or
    username string respectively.  The pair ``(scope, key)`` is unique — one
    row per tracked entity.  A row is deleted on successful login (clear).
    """

    __tablename__ = "auth_login_throttle"
    __table_args__ = (
        UniqueConstraint("scope", "key", name="uq_auth_login_throttle_scope_key"),
        Index("ix_auth_login_throttle_scope_key", "scope", "key"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    key: Mapped[str] = mapped_column(String(255), nullable=False)
    scope: Mapped[str] = mapped_column(String(16), nullable=False)  # 'ip' | 'user'
    failures: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    first_failed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    last_failed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    next_allowed_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
