from __future__ import annotations

from datetime import datetime

from sqlalchemy import BigInteger, DateTime, ForeignKey, String
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.models.base import Base, TimestampMixin


class Knowledge(Base, TimestampMixin):
    __tablename__ = "sys_knowledge"

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String(100), nullable=False)
    feishu_space_id: Mapped[str] = mapped_column(String(100), nullable=False)
    feishu_node_id: Mapped[str] = mapped_column(String(100), nullable=False)
    status: Mapped[int] = mapped_column(default=1, nullable=False)
    remark: Mapped[str | None] = mapped_column(String(255), nullable=True)

    user_permissions: Mapped[list["UserKnowledgePermission"]] = relationship(
        "UserKnowledgePermission", back_populates="knowledge"
    )


class UserKnowledgePermission(Base, TimestampMixin):
    __tablename__ = "sys_user_kb"

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("sys_user.id"), index=True, nullable=False)
    knowledge_id: Mapped[int] = mapped_column(ForeignKey("sys_knowledge.id"), index=True, nullable=False)
    effective_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    expired_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    created_by: Mapped[int | None] = mapped_column(BigInteger, nullable=True)

    user: Mapped["User"] = relationship("User", back_populates="knowledge_permissions")
    knowledge: Mapped[Knowledge] = relationship("Knowledge", back_populates="user_permissions")
