import datetime
import typing

from sqlmodel import SQLModel, Field, Relationship
import typing as tp
import ipaddress
from sqlalchemy import UniqueConstraint

if tp.TYPE_CHECKING:
    from .user import User


class LoginToken(SQLModel, table=True):
    __tablename__:str = "login_tokens" # type: ignore
    __table_args__ = (UniqueConstraint("token"),)
    id: int = Field(primary_key=True)
    token: str  # 校验token
    expired_in: typing.Optional[datetime.datetime]  # 过期时间
    user_id: int = Field(foreign_key="user.id")  # 关联用户
    user: User = Relationship(back_populates="tokens")


class LoginLog(SQLModel, table=True):
    __tablename__:str = "login_logs" # type: ignore
    id: int = Field(primary_key=True)
    user_id: int = Field(foreign_key="users.id", index=True)  # 关联用户
    user: User = Relationship(back_populates="login_logs", link_model="User")
    login_time: datetime.datetime = Field(
        default_factory=lambda: datetime.datetime.utcnow
    )  # 登录时间
    custom_ip: typing.Optional[ipaddress.IPv4Address]  # 登录用户IP

sqlmodel.Relationship sqlmodel.Field sqlalchemy.UniqueConstraint
[((368, 391), 'sqlmodel.Field', 'Field', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (373, 391), False, 'from sqlmodel import SQLModel, Field, Relationship\n'), ((496, 524), 'sqlmodel.Field', 'Field', ([], {'foreign_key': '"""user.id"""'}), "(foreign_key='user.id')\n", (501, 524), False, 'from sqlmodel import SQLModel, Field, Relationship\n'), ((550, 587), 'sqlmodel.Relationship', 'Relationship', ([], {'back_populates': '"""tokens"""'}), "(back_populates='tokens')\n", (562, 587), False, 'from sqlmodel import SQLModel, Field, Relationship\n'), ((694, 717), 'sqlmodel.Field', 'Field', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (699, 717), False, 'from sqlmodel import SQLModel, Field, Relationship\n'), ((737, 778), 'sqlmodel.Field', 'Field', ([], {'foreign_key': '"""users.id"""', 'index': '(True)'}), "(foreign_key='users.id', index=True)\n", (742, 778), False, 'from sqlmodel import SQLModel, Field, Relationship\n'), ((804, 864), 'sqlmodel.Relationship', 'Relationship', ([], {'back_populates': '"""login_logs"""', 'link_model': '"""User"""'}), "(back_populates='login_logs', link_model='User')\n", (816, 864), False, 'from sqlmodel import SQLModel, Field, Relationship\n'), ((901, 957), 'sqlmodel.Field', 'Field', ([], {'default_factory': '(lambda : datetime.datetime.utcnow)'}), '(default_factory=lambda : datetime.datetime.utcnow)\n', (906, 957), False, 'from sqlmodel import SQLModel, Field, Relationship\n'), ((326, 351), 'sqlalchemy.UniqueConstraint', 'UniqueConstraint', (['"""token"""'], {}), "('token')\n", (342, 351), False, 'from sqlalchemy import UniqueConstraint\n')]