from sqlalchemy import JSON, Column, DateTime, Integer, String, Text
from sqlalchemy.sql import func

from app.models.base import Base


class AuditLog(Base):
    __tablename__ = "audit_logs"
    __table_args__ = {"schema": "public"}
    id = Column(Integer, primary_key=True, index=True)
    tenant_id = Column(
        Integer, nullable=True, index=True, comment="Tenant ID (null for platform operations)"
    )
    user_id = Column(Integer, nullable=True, index=True, comment="User ID who performed the action")
    action = Column(
        String(50),
        nullable=False,
        index=True,
        comment="Action type: create, read, update, delete, execute, login, logout",
    )
    resource_type = Column(
        String(50),
        nullable=False,
        index=True,
        comment="Resource type: agent, knowledge_base, user, tenant, etc.",
    )
    resource_id = Column(Integer, nullable=True, comment="ID of the affected resource")
    request_method = Column(String(10), comment="HTTP method: GET, POST, PUT, DELETE, PATCH")
    request_path = Column(Text, comment="Request path")
    ip_address = Column(String(45), comment="Client IP address")
    user_agent = Column(Text, comment="User agent string")
    request_data = Column(JSON, comment="Request parameters (sanitized)")
    response_status = Column(Integer, comment="HTTP response status code")
    error_message = Column(Text, comment="Error message if request failed")
    duration_ms = Column(Integer, comment="Request duration in milliseconds")
    request_size_bytes = Column(Integer, comment="Request payload size in bytes")
    response_size_bytes = Column(Integer, comment="Response payload size in bytes")
    bandwidth_bytes = Column(Integer, comment="Total bandwidth (request + response) in bytes")
    created_at = Column(
        DateTime(timezone=True), server_default=func.now(), nullable=False, index=True
    )
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())

    def __repr__(self):
        return f"<AuditLog(id={self.id}, action={self.action}, resource_type={self.resource_type}, user_id={self.user_id})>"
