# @File: models/oauth_state.py
# @Desc: Short-lived per-attempt OAuth state row. Stores the anti-CSRF state
#        token, the PKCE code_verifier, the provider slug, and the post-login
#        mode (login vs register) so the callback handler knows where to send
#        the user back to. Rows are single-use and expire after 10 minutes.
from datetime import datetime

from models.base import Base
from sqlalchemy import Column, DateTime, Integer, String
from sqlalchemy.sql import func


class OAuthState(Base):
    __tablename__ = "oauth_states"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    state = Column(String(128), unique=True, index=True, nullable=False)
    provider = Column(String(32), nullable=False)
    code_verifier = Column(String(255), nullable=False)
    # "login" or "register" — used purely to pick a sensible redirect target
    # after the OAuth round-trip completes (both currently go to /dashboard).
    mode = Column(String(16), nullable=False, default="login")
    # Where to send the user back to on success / failure (frontend URL).
    return_to = Column(String(512), nullable=True)
    expires_at = Column(DateTime(timezone=True), nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())

    def is_expired(self) -> bool:
        now = datetime.utcnow()
        exp = self.expires_at
        # expires_at is timezone-aware; compare with an aware "now" when needed.
        if exp is None:
            return True
        if exp.tzinfo is not None:
            from datetime import timezone

            return datetime.now(timezone.utc) >= exp
        return now >= exp