"""
操作日志数据模型
"""
from datetime import datetime
from sqlalchemy import Column, BigInteger, String, Text, Integer, DateTime, Index
from sqlalchemy.dialects.postgresql import JSONB
from app.db.base import Base


class OperationLog(Base):
    """操作日志表"""

    __tablename__ = "operation_logs"

    id = Column(BigInteger, primary_key=True, index=True)
    operator_id = Column(BigInteger, nullable=False, index=True, comment="操作人ID")
    operator_name = Column(String(100), nullable=False, comment="操作人姓名")
    operator_ip = Column(String(50), nullable=True, comment="操作人IP")
    module = Column(String(50), nullable=False, index=True, comment="模块名称")
    operation_type = Column(String(50), nullable=False, index=True, comment="操作类型")
    method = Column(String(10), nullable=False, comment="请求方法(GET/POST/PUT/DELETE等)")
    url = Column(String(500), nullable=False, comment="请求URL")
    params = Column(Text, nullable=True, comment="请求参数")
    result = Column(String(20), default="success", nullable=False, comment="操作结果: success/failed")
    error_msg = Column(Text, nullable=True, comment="错误信息")
    duration = Column(Integer, nullable=True, comment="执行时长(毫秒)")
    user_agent = Column(String(500), nullable=True, comment="用户代理")
    extra_data = Column(JSONB, nullable=True, comment="额外数据")
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, index=True)

    # 索引
    __table_args__ = (
        Index("idx_operation_log_operator", "operator_id"),
        Index("idx_operation_log_module", "module"),
        Index("idx_operation_log_time", "created_at"),
        Index("idx_operation_log_result", "result"),
    )

    def __repr__(self):
        return f"<OperationLog(id={self.id}, operator={self.operator_name}, module={self.module}, operation={self.operation_type})>"
