"""
文件管理数据模型
"""
from datetime import datetime
from sqlalchemy import Column, BigInteger, String, DateTime, Text, Index, Boolean, ForeignKey
from sqlalchemy.orm import relationship
from app.db.base import Base


class UploadedFile(Base):
    """上传文件表"""

    __tablename__ = "uploaded_files"

    id = Column(BigInteger, primary_key=True, index=True)
    file_name = Column(String(255), nullable=False, comment="存储文件名(UUID)")
    original_name = Column(String(255), nullable=False, index=True, comment="原始文件名")
    file_path = Column(String(500), nullable=False, comment="文件存储路径")
    file_size = Column(BigInteger, nullable=False, comment="文件大小(字节)")
    file_type = Column(String(100), nullable=False, index=True, comment="文件类型(MIME)")
    file_ext = Column(String(50), nullable=False, comment="文件扩展名")
    uploader_id = Column(BigInteger, ForeignKey("users.id"), nullable=True, comment="上传人ID")
    upload_time = Column(DateTime, default=datetime.utcnow, nullable=False, index=True, comment="上传时间")
    thumbnail_path = Column(String(500), nullable=True, comment="缩略图路径")
    share_code = Column(String(100), nullable=True, unique=True, index=True, comment="分享码")
    share_expire_time = Column(DateTime, nullable=True, index=True, comment="分享过期时间")
    download_count = Column(BigInteger, default=0, comment="下载次数")
    is_deleted = Column(Boolean, default=False, nullable=False, comment="是否删除")
    deleted_at = Column(DateTime, nullable=True, comment="删除时间")
    deleted_by = Column(BigInteger, ForeignKey("users.id"), nullable=True, comment="删除人ID")
    remark = Column(Text, nullable=True, comment="备注")
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

    # 关系
    uploader = relationship("User", foreign_keys=[uploader_id])
    deleter = relationship("User", foreign_keys=[deleted_by])

    # 索引
    __table_args__ = (
        Index("idx_uploaded_files_uploader", "uploader_id"),
        Index("idx_uploaded_files_deleted", "is_deleted"),
    )

    def __repr__(self):
        return f"<UploadedFile(id={self.id}, original_name={self.original_name}, file_type={self.file_type})>"
