"""
令牌相关数据模型
"""
from sqlalchemy import Column, String, Boolean, DateTime, Text, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.mysql import CHAR
from .base import BaseModel
from datetime import datetime


class OAuthAccessToken(BaseModel):
    """访问令牌表"""
    __tablename__ = "t_oauth_access_tokens"
    
    user_id = Column(CHAR(36), ForeignKey("t_sys_user.id", ondelete="CASCADE"), nullable=False, comment="用户ID")
    app_id = Column(CHAR(36), ForeignKey("t_sys_app.id", ondelete="CASCADE"), nullable=True, comment="应用ID（系统内部登录时可为空）")
    token = Column(String(512), unique=True, nullable=False, comment="访问令牌")
    refresh_token = Column(String(512), unique=True, nullable=True, comment="刷新令牌")
    token_type = Column(String(50), default="Bearer", comment="令牌类型")
    scope = Column(String(500), nullable=True, comment="权限范围")
    expires_at = Column(DateTime, nullable=False, comment="过期时间")
    revoked = Column(Boolean, default=False, comment="是否撤销")
    last_used_at = Column(DateTime, nullable=True, comment="最后使用时间")
    
    # 关联关系
    user = relationship("User", back_populates="tokens")
    app = relationship("App", back_populates="tokens")


class OAuthAuthorizationCode(BaseModel):
    """授权码表"""
    __tablename__ = "t_oauth_authorization_codes"
    
    user_id = Column(CHAR(36), ForeignKey("t_sys_user.id", ondelete="CASCADE"), nullable=False, comment="用户ID")
    app_id = Column(CHAR(36), ForeignKey("t_sys_app.id", ondelete="CASCADE"), nullable=False, comment="应用ID")
    code = Column(String(100), unique=True, nullable=False, comment="授权码")
    redirect_uri = Column(String(500), nullable=False, comment="回调URL")
    scope = Column(String(500), nullable=True, comment="权限范围")
    expires_at = Column(DateTime, nullable=False, comment="过期时间")
    used = Column(Boolean, default=False, comment="是否已使用")
    
    # 关联关系
    user = relationship("User")
    app = relationship("App", back_populates="authorization_codes")


class TokenBlacklist(BaseModel):
    """令牌黑名单表"""
    __tablename__ = "t_oauth_token_blacklist"
    
    token = Column(String(512), unique=True, nullable=False, comment="令牌")
    token_type = Column(String(50), nullable=True, comment="令牌类型")
    expires_at = Column(DateTime, nullable=False, comment="过期时间")
    added_at = Column(DateTime, default=datetime.utcnow, comment="加入时间")
    reason = Column(String(200), nullable=True, comment="加入原因")