from datetime import datetime
import uuid
from typing import Optional

from sqlmodel import SQLModel, Field


class UserSessionDB(SQLModel, table=True):
    """用户会话表 - 持久化 refresh token 会话状态"""

    __tablename__ = "user_sessions"

    id: str = Field(default_factory=lambda: str(uuid.uuid4()), primary_key=True)
    user_id: str = Field(foreign_key="users.id", index=True, description="关联用户 ID")
    session_family_id: str = Field(
        default_factory=lambda: str(uuid.uuid4()),
        index=True,
        description="同一刷新链的会话族 ID",
    )
    refresh_token_hash: str = Field(index=True, description="Refresh token 的哈希值")
    status: str = Field(default="active", index=True, description="会话状态")

    created_at: float = Field(default_factory=lambda: datetime.now().timestamp(), description="创建时间")
    updated_at: float = Field(default_factory=lambda: datetime.now().timestamp(), description="更新时间")
    expires_at: float = Field(description="Refresh token 过期时间")
    last_used_at: Optional[float] = Field(default=None, description="最后使用时间")
    revoked_at: Optional[float] = Field(default=None, index=True, description="撤销时间")
    revoked_reason: Optional[str] = Field(default=None, description="撤销原因")
    replaced_by_session_id: Optional[str] = Field(default=None, description="轮换后替代它的新会话 ID")

    ip_address: Optional[str] = Field(default=None, description="登录 IP")
    user_agent: Optional[str] = Field(default=None, description="User-Agent")
    device_name: Optional[str] = Field(default=None, description="设备名称")
