"""
数据源模型
"""
from sqlalchemy import Column, String, Text, DateTime, JSON, ForeignKey, func
from sqlalchemy.dialects.mysql import CHAR
from sqlalchemy.orm import relationship
from app.core.database import Base
import uuid


class DataSource(Base):
    """数据源表"""
    __tablename__ = "data_sources"

    id = Column(CHAR(36), primary_key=True, default=lambda: str(uuid.uuid4()), comment="数据源ID")
    name = Column(String(100), nullable=False, comment="数据源名称")
    type = Column(String(50), nullable=False, comment="数据源类型: mysql/postgresql/mongodb/redis/csv/json/api/s3")
    description = Column(Text, comment="描述")
    config = Column(JSON, nullable=False, comment="连接配置（加密存储敏感信息）")
    status = Column(String(20), default="active", comment="状态: active/inactive/error")
    user_id = Column(CHAR(36), ForeignKey("users.id"), nullable=False, comment="创建者ID")
    last_connected_at = Column(DateTime, comment="最后连接时间")
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")

    # 关系
    user = relationship("User", backref="data_sources")

    def __repr__(self):
        return f"<DataSource(id={self.id}, name={self.name}, type={self.type})>"
