from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Boolean
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.core.database import Base


class AdminApiKey(Base):
    """管理员级 API Key（永久凭证）。

    专用于调用一组独立的 /admin-api/* 接口。明文 Key 仅在创建时返回一次，
    数据库仅保存 bcrypt 哈希与前缀。不支持物理删除：仅 禁用(可恢复) / 吊销(永久作废)。
    """

    __tablename__ = "admin_api_keys"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False, comment="Key 名称/用途备注")
    description = Column(Text, nullable=True)

    key_prefix = Column(String(16), nullable=False, index=True, comment="Key 前缀（明文前 12 字符）")
    key_hash = Column(String(128), nullable=False, unique=True, comment="bcrypt(key)")

    scopes = Column(
        String(255),
        nullable=False,
        default="user:read,user:write,org:read,org:write",
        comment="逗号分隔的权限范围",
    )

    is_active = Column(Boolean, nullable=False, default=True, comment="启用 / 禁用（可恢复）")
    is_revoked = Column(Boolean, nullable=False, default=False, comment="已吊销（永久作废）")

    created_by = Column(Integer, ForeignKey("users.id"), nullable=False)
    last_used_at = Column(DateTime(timezone=True), nullable=True)
    last_used_ip = Column(String(64), nullable=True)
    use_count = Column(Integer, nullable=False, default=0)

    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), server_default=func.now())

    creator = relationship("User", foreign_keys=[created_by])
