"""
应用相关数据模型
"""
from sqlalchemy import Column, String, Boolean, Integer, Text, JSON, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.mysql import CHAR
from .base import BaseModel


class App(BaseModel):
    """应用表"""
    __tablename__ = "t_sys_app"
    
    name = Column(String(100), nullable=False, comment="应用名称")
    app_key = Column(String(100), unique=True, nullable=False, comment="应用Key")
    app_secret = Column(String(255), nullable=False, comment="应用Secret")
    description = Column(Text, nullable=True, comment="应用描述")
    icon_url = Column(String(500), nullable=True, comment="应用图标")
    redirect_uris = Column(JSON, nullable=False, comment="回调URL列表")
    scope = Column(JSON, nullable=True, comment="权限范围")
    is_active = Column(Boolean, default=True, comment="是否激活")
    is_trusted = Column(Boolean, default=False, comment="是否受信任应用")
    access_token_expires = Column(Integer, default=7200, comment="访问令牌过期时间(秒)")
    refresh_token_expires = Column(Integer, default=2592000, comment="刷新令牌过期时间(秒)")
    
    # 关联关系
    permissions = relationship("AppPermission", back_populates="app")
    tokens = relationship("OAuthAccessToken", back_populates="app")
    authorization_codes = relationship("OAuthAuthorizationCode", back_populates="app")
    sync_logs = relationship("SyncLog", back_populates="app")


class AppPermission(BaseModel):
    """应用权限表"""
    __tablename__ = "t_sys_app_permission"
    
    app_id = Column(CHAR(36), ForeignKey("t_sys_app.id", ondelete="CASCADE"), nullable=False, comment="应用ID")
    permission_code = Column(String(100), nullable=False, comment="权限代码")
    permission_name = Column(String(100), nullable=False, comment="权限名称")
    description = Column(String(500), nullable=True, comment="权限描述")
    
    # 关联关系
    app = relationship("App", back_populates="permissions")